Sub topic 13
Composition or inheritance: choosing a design
This chapter assumes you can define classes with __init__ and methods, subclass with super(), and know that Python looks up methods through the MRO (method resolution order). Here you learn how to decide between two ways of reusing code.
Two relationships
Inheritance models an is-a relationship. A Dog is an Animal, so it can be used wherever an Animal is expected.
Composition models a has-a relationship. A Car has an Engine, so Car stores an engine object in an attribute and delegates work to it.
Both reuse code. They differ in how tightly the new class is tied to the old one.
Composition in practice
class Engine:
def start(self):
return "engine started"
class ElectricMotor:
def start(self):
return "motor humming"
class Car:
def __init__(self, engine=None):
self.engine = engine if engine is not None else Engine()
def start(self):
return self.engine.start()
print(Car().start()) # engine started
print(Car(ElectricMotor()).start()) # motor hummingCar does not care which class its engine comes from, as long as the object has start(). This is duck typing applied to design. You can change behavior by passing a different part, without creating a new subclass of Car.
When inheritance backfires
A subclass inherits every public method of its parent, including the ones you do not want. Here is a stack built on list:
class Stack(list):
def push(self, item):
self.append(item)
s = Stack()
s.push(1)
s.push(2)
s.insert(0, 99) # legal, but a stack should not allow this
print(s) # [99, 1, 2]Stack is not really a kind of list. It only needs part of a list's behavior. Composition exposes only what you choose:
class Stack:
def __init__(self):
self._items = []
def push(self, item):
self._items.append(item)
def pop(self):
return self._items.pop()
def __len__(self):
return len(self._items)
s = Stack()
s.push(1)
s.push(2)
print(s.pop(), len(s)) # 2 1The internal list can change later, for example to a collections.deque, and no caller breaks.
Deciding
| Question | Leans toward |
|---|---|
| Is the new class truly a special case of the parent, usable anywhere the parent is? | Inheritance |
| Do you want only some of the other class's behavior? | Composition |
| Must the behavior be swappable at runtime or in tests? | Composition |
| Does the parent class expect to be subclassed (a framework base class, an ABC)? | Inheritance |
| Would you need several parents, risking a tangled MRO? | Composition |
Common mistakes
- Inheriting only to reuse code. If the "is-a" sentence sounds wrong ("a Stack is a list"), use composition.
- Deep hierarchies. Each level adds methods that readers must check. Keep hierarchies shallow.
- Breaking substitutability. If a subclass raises an error for a method the parent supports, code written for the parent fails when it receives the subclass.
- Forgetting to delegate. With composition you must write the forwarding methods yourself, or callers will reach through
car.enginedirectly.
Exercise
A Logger class has info() and error() methods. A teammate writes class OrderService(Logger) so that OrderService can log. Is inheritance a good choice? What would you write instead?
Show answer
No. An order service is not a kind of logger, and inheriting makes info() and error() part of its public interface. Use composition: store self.logger = logger in __init__ (passed in as an argument) and call self.logger.info(...) inside methods. Tests can then pass in a fake logger.