← Back to Python

All Topics

Advertisement

Learn/Python/Advanced Python

Abstract Base Classes

Topic: OOP

Advertisement

Introduction

Abstract Base Classes (ABCs) define interfaces that derived classes must implement.

Defining ABCs

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass
    
    @abstractmethod
    def perimeter(self):
        pass
    
    def display(self):
        print(f"Area: {self.area()}")

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height
    
    def area(self):
        return self.width * self.height
    
    def perimeter(self):
        return 2 * (self.width + self.height)

Registering Implementations

@Shape.register
class Triangle:
    def __init__(self, base, height):
        self.base = base
        self.height = height
    
    def area(self):
        return 0.5 * self.base * self.height

Checking Implementation

from abc import ABCMeta

class MyABC(metaclass=ABCMeta):
    @abstractmethod
    def method(self):
        pass

MyABC.register(list)  # Register list as implementing MyABC
print(isinstance([], MyABC))  # True

Practice Problems

  1. Create ABC for animal hierarchy
  2. Define abstract factory pattern with ABC
  3. Register non-subclass as virtual subclass
  4. Combine abstract methods with concrete ones
  5. Use ABC to enforce plugin architecture

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →