Sub topic 13
When to prefer composition
This chapter assumes you can write subclasses, override methods, call super(), and read a basic method resolution order. It covers when inheritance is the wrong tool and what to use instead.
Is-a versus has-a
Inheritance models an "is-a" relationship. A Dog is an Animal, so code that accepts an Animal can accept a Dog.
Composition models a "has-a" relationship. One object holds another object in an attribute and calls its methods. A Car has an Engine, but a car is not an engine.
Inheritance ties a subclass to everything in its parent: public methods, internal attributes, and future changes. Composition ties the two classes only through the methods you choose to call.
A subclass that exposes too much
Suppose you want a stack and subclass list to save work:
class ListStack(list):
def push(self, item):
self.append(item)
s = ListStack()
s.push(1)
s.push(2)
s.insert(0, 99) # legal, but a stack should not allow this
print(s) # [99, 1, 2]ListStack is-a list, so it inherits insert(), sort(), remove(), and dozens of other methods. Callers can break the stack's rules, and you can never remove those methods without breaking callers. This is a substitutability problem. The subclass promises everything the parent does, and it cannot keep that promise while also enforcing stack behavior.
The same design with composition
Hold a list privately and expose only the operations a stack needs:
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 1
print(hasattr(s, "insert")) # FalseThe public interface is exactly what you wrote. You can later replace the list with a collections.deque and no caller will notice. Forwarding a call to the held object, as push() does here, is called delegation.
Swapping behavior at run time
Inheritance fixes behavior when you write the class. Composition lets you choose it when you create the object, or change it later:
class EmailSender:
def send(self, to, text):
return f"email to {to}: {text}"
class SmsSender:
def send(self, to, text):
return f"sms to {to}: {text}"
class Alert:
def __init__(self, sender):
self.sender = sender
def fire(self, to):
return self.sender.send(to, "Server down")
print(Alert(EmailSender()).fire("ops")) # email to ops: Server down
print(Alert(SmsSender()).fire("ops")) # sms to ops: Server downWith inheritance you would need EmailAlert and SmsAlert subclasses, and a third class for each new combination of features. Here Alert works with any object that has a send() method, which is polymorphism without a shared parent.
Choosing between them
| Question | Leans toward inheritance | Leans toward composition |
|---|---|---|
| Is the relationship "is-a" in every case? | Yes | No, it is "has-a" or "uses" |
| Can a subclass honor every parent method? | Yes | No, you would disable or change some |
| Do you need to change behavior at run time? | No | Yes |
| Are you reusing code only for convenience? | No | Yes |
| Do parent and child change together? | Yes | They change independently |
Where mixins fit
A mixin sits between the two approaches. It adds one focused behavior through inheritance, but it is not meant to be a parent type. Use a mixin when the behavior depends only on the host class's own data, as JsonMixin did. If the behavior needs its own state, or you may want to swap it out, hold it as an attribute instead.
Common mistakes
- Inheriting from a built-in container such as
listordictonly to reuse a few methods. - Building deep hierarchies where each level adds a small feature. Each level raises the cost of reading the code, because you must check several classes to know which method runs.
- Choosing inheritance because it takes fewer lines now. The cost appears later, when the parent changes.
Neither tool is always right. Inheritance is a good fit for a real type hierarchy with a stable parent, such as a set of shapes that all implement area(). Composition is the safer default when you are unsure.
Exercise
A Report class needs to write its text to a file, and later to a database. A teammate proposes class Report(FileWriter) and then class DbReport(Report) overriding the writing method. Describe a composition design instead and name one advantage.
Show answer
Give Report an attribute such as self.writer, passed to __init__, and have Report.save() call self.writer.write(text). Create small FileWriter and DbWriter classes that each have a write() method. An advantage is that the destination is chosen when the object is created, or changed later, without new Report subclasses. A report is also not a kind of file writer, so the "is-a" test fails for the proposed design.
Exercise
Why is class Stack(list) a weaker design than a Stack class that holds a list in self._items?
Show answer
The subclass inherits every list method, including insert() and sort(), so callers can break stack behavior and you cannot remove those methods later. The composed version exposes only push(), pop(), and __len__(), and lets you change the internal storage freely.