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
- Create ABC for animal hierarchy
- Define abstract factory pattern with ABC
- Register non-subclass as virtual subclass
- Combine abstract methods with concrete ones
- Use ABC to enforce plugin architecture