Sub topic 3
Requiring Overrides with Abstract Base Classes
Assume you can define classes, create instances, and write instance methods. This chapter focuses on designs where subclasses must provide specific behavior.
Requiring overrides with abstract base classes
An abstract base class defines a shared interface without allowing incomplete objects. Use ABC and @abstractmethod from the abc module:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
"""Return the shape's area."""
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
shapes = [Square(2), Square(3)]
print([shape.area() for shape in shapes]) # [4, 9]
try:
Shape()
except TypeError as error:
print("Cannot create Shape:", error)Shape() fails because it does not implement area(). Square is concrete because it does.
Reading the method resolution order
The method resolution order (MRO) is the sequence Python uses to find methods and attributes. Read it with __mro__ or mro().
class A:
def name(self):
return ["A"]
class B(A):
def name(self):
return ["B"] + super().name()
class C(A):
def name(self):
return ["C"] + super().name()
class D(B, C):
def name(self):
return ["D"] + super().name()
print(D().name()) # ['D', 'B', 'C', 'A']
print([item.__name__ for item in D.__mro__])Python visits D, B, C, and A once each. Every method uses super(), so the chain remains cooperative.
Multiple inheritance and the diamond problem
The diamond problem occurs when two classes share the same parent. Calling a parent directly can run shared code twice or skip another class. Cooperative super() calls let Python follow the MRO safely.
Adding behavior with mixins
A mixin is a small class that adds one focused capability. It usually does not represent a complete standalone object.
import json
class JsonMixin:
def to_json(self):
return json.dumps(self.__dict__)
class Point(JsonMixin):
def __init__(self, x, y):
self.x = x
self.y = y
print(Point(1, 2).to_json())Overriding without breaking callers
A subclass should preserve the parent method's expected inputs, outputs, and guarantees. Code that accepts the parent type should also work with the subclass. This is substitutability. Do not make an override reject valid parent inputs or return an incompatible result.
When to prefer composition
Inheritance expresses an “is a” relationship. Composition gives an object another object to use and often keeps designs simpler. Prefer composition when behavior may change independently, when the relationship is “has a,” or when multiple inheritance would be difficult to understand.
Exercise
Why does D().name() return ['D', 'B', 'C', 'A']?
Show answer
D, B, C, and A each call super(), so Python follows D's MRO and invokes every method once.