What are Abstract Base Classes (ABCs)?
In Object-Oriented Programming (OOP), an Abstract Base Class is a class that cannot be instantiated. It's used as a formal blueprint (interface) for other classes to inherit from. It defines common methods that its subclasses must implement.
python
Why Use ABCs?
- Enforce Interface Consistency: Ensures all subclasses share a common set of methods.
- Early Error Detection: If a subclass forgets to implement an
@abstractmethod, Python will raise an error when you try to create the object, not when the method is eventually called. - Better Code Architecture: Makes it clear to other developers how to extend your project.
Creating Concrete Subclasses
A concrete class is a subclass that implements all required abstract methods.
python
Abstract Properties: @property + @abstractmethod
You can also require subclasses to provide certain attributes as properties.
python
Virtual Subclasses: Registering Existing Classes
Python allows you to "register" a class as a subclass of an ABC even if it doesn't actually inherit from it. This is useful for third-party libraries.
python
Building Robust APIs: Type Checking
Because ABCs provide a formal interface, you can safely use them for type checking in your functions.
python
Summary
| Feature | Description |
|---|---|
| ABC | Any class inheriting from abc.ABC |
| @abstractmethod | Decorator for methods that MUST be overridden |
| Instantiation | Impossible for ABCs; raises TypeError! |
| Registration | Register virtual subclasses with .register() |
| Interface | Formally define behavior for a group of classes |
| Best For | Plugin systems, DB adapters, shape libraries |
| Subclassing | Subclassing an ABC requires implementing ALL abstract methods |
| Virtual Subclass | Classes that "fit the bill" without inheriting |
| issubclass() | Check if a class implements an ABC |
| isinstance() | Check if an object belongs to an ABC hierarchy |