🏗 Abstract Base Classes (ABC) in Python
Abstract Base Classes (ABCs) provide a way to define interfaces and enforce a contract for derived classes. They cannot be instantiated directly and often contain abstract methods that must be implemented by subclasses.
🧠 Why use ABCs?
- Enforce Interfaces: Ensure subclasses implement specific methods.
- Type Checking: Use
isinstance()andissubclass()to check against the abstract base class. - Documentation: Clearly define what methods are expected.
🛠 Creating an ABC
Use the abc module. Inherit from ABC and use the @abstractmethod decorator.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
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)
# s = Shape() # TypeError: Can't instantiate abstract class Shape
r = Rectangle(5, 10)
print(r.area()) # 50
👻 Virtual Subclasses
You can register a class as a "virtual subclass" of an ABC, even if it doesn't inherit from it. This is useful for checking if a class adheres to a protocol.
from abc import ABC
class MyABC(ABC):
pass
class MyClass:
pass
MyABC.register(MyClass)
print(issubclass(MyClass, MyABC)) # True
print(isinstance(MyClass(), MyABC)) # True
🧩 Abstract Properties
You can also define abstract properties.
from abc import ABC, abstractmethod
class Base(ABC):
@property
@abstractmethod
def value(self):
pass
class Concrete(Base):
@property
def value(self):
return 42
📝 Summary
- ✅ Contract: Defines a blueprint for subclasses.
- ✅ Safety: Prevents instantiation of incomplete classes.
- ✅ Polymorphism: Allows treating different objects uniformly based on their interface.
Created with ❤️ by Pynfinity