Polymorphism & Abstraction
Abstract Classes
Defining interfaces with the abc module
Interview: Design patterns — tests understanding of interfaces, abstract methods, and enforcement of contracts
Abstract classes define a common interface that subclasses must implement. Python provides the abc module (Abstract Base Classes) for this purpose. Abstract classes cannot be instantiated directly — they serve as blueprints for concrete subclasses. This enforces a contract that ensures all subclasses implement required methods.
Key Concepts
- Inherit from
ABC(or useABCMetametaclass) - Use
@abstractmethoddecorator to mark required methods - Cannot instantiate a class with unimplemented abstract methods
- Abstract classes can have concrete methods (shared implementation)
- Abstract properties with
@property+@abstractmethod
When to Use Abstract Classes
- Defining a common API for multiple implementations
- Plugin systems where plugins must implement specific methods
- Framework design: base classes that enforce implementation contracts
- When duck typing isn't enough — you need compile-time/instantiation-time enforcement
Common Pitfall
Abstract methods with a default implementation still MUST be overridden in subclasses. The default body (even pass) is not automatically inherited — Python checks for explicit implementation.
Use Cases
Defining plugin interfaces that all plugins must implement
Repository pattern for data access layers (DB, API, in-memory)
Strategy pattern: interchangeable algorithms with common interface
Framework design: base handlers, serializers, validators
Enforcing contracts in team codebases (prevents forgetting to implement methods)
Common Mistakes
Forgetting to inherit from ABC — abstract methods won't be enforced
Not implementing all abstract methods — subclass can't be instantiated
Using abstract classes when a Protocol would be simpler (structural typing)
Putting too much logic in abstract base classes (violates interface segregation)
Forgetting that @property + @abstractmethod requires both decorators in correct order