Python Abstract Base Classes (abc)
Abstract Base Classes (ABCs) provide a way to define interfaces when other techniques like hasattr() would be clumsy or subtly wrong (for example, with magic methods). They allow you to define a blueprint for a class, enforcing that derived classes implement specific methods.
Importing the Module
from abc import ABC, abstractmethod
Defining an Abstract Base Class
To create an ABC, you inherit from the ABC class.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
Concrete Implementation
A class that inherits from an ABC must implement all abstract methods to be instantiated.
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)
rect = Rectangle(10, 20)
print(f"Area: {rect.area()}")
print(f"Perimeter: {rect.perimeter()}")
If you try to instantiate Shape directly or a subclass that doesn't implement all abstract methods, Python raises a TypeError.
Virtual Subclasses
You can also register a class as a virtual subclass of an ABC using the register method. This makes issubclass and isinstance return True, but it doesn't enforce method implementation.
class MyClass:
def area(self):
return 0
Shape.register(MyClass)
print(issubclass(MyClass, Shape)) # Output: True
print(isinstance(MyClass(), Shape)) # Output: True