Inheritance Vs Composition
"Favor object composition over class inheritance." — Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, Design Patterns (1994), GoF
"Inheritance is a powerful way to achieve code reuse, but it is not always the best tool for the job. Used inappropriately, it leads to fragile software." — Joshua Bloch, Effective Java, Item 18
Core idea
Inheritance (is-a) — the class gets everything from the parent and is tightly coupled to its implementation.
Composition (has-a) — the class owns another object and calls its methods through the public contract.
Composition is almost always more flexible, testable, and reliable. Inheritance is a tool that is allowed, but rarely the right choice.
What inheritance is, and why it is dangerous
class Animal:
def breathe(self): print("breathing")
def eat(self): print("eating")
class Dog(Animal):
def bark(self): print("woof")
Dog gets everything from Animal: all the methods, all the attributes, and all the future changes to Animal. This is tight coupling: parent and child depend on each other through the private representation.
The classic problem:
class Animal:
def breathe(self):
self.eat() # the author of Animal decided breathing means eating
print("breathing")
class Robot(Animal): # the child depends on the parent's INTERNAL behaviour
def eat(self):
raise NotImplementedError("robots do not eat")
Now Robot().breathe() crashes, even though no one touched Robot. This is called the Fragile Base Class problem.
Why composition is almost always better
| Inheritance | Composition |
|---|---|
| The link is rigid, at the internal level | The link is soft, through the interface |
| The structure is set at the time the class is written | You can swap in a different object at runtime |
| A change in the parent can break every child | A change in one object does not touch the others |
| Testing a subclass means lifting all the parent state | Testing means passing in a mock object |
| One parent (single inheritance) | As many components as you want |
| Method allow / deny is governed by hard rules (LSP) | No restrictions, you call what you need |
Joshua Bloch (author of large parts of the Java standard library, Effective Java): "Inheritance violates encapsulation." The subclass sees the parent's internals, not its contract.
Classic anti-pattern: Stack extends List
This example lives in Effective Java and still gets developers to say "oh, that is exactly right".
❌ Through inheritance
class Stack(list):
def push(self, item):
self.append(item)
def pop_top(self):
return self.pop()
Problems:
- Foreign methods leak through.
Stackhasinsert(),remove(),clear(),reverse(),sort(). None of them make sense for a stack. Someone can calls.insert(0, "evil")and break the semantics of a stack without breaking any check. s[0]works. Direct index access is not a stack, it is a list.- You cannot swap the storage. Tomorrow you might want
collections.deque(faster pop from the head for a queue, or some other structure). You cannot, you are already alist. - Any new method on
listautomatically appears onStackand may clash with your own name. - You cannot restrict the element type.
s.append(...)next tos.push(...)is two ways to add an element. No invariant.
✅ Through composition
class Stack:
def __init__(self):
self._items: list = [] # the internal storage is a detail
def push(self, item) -> None:
self._items.append(item)
def pop(self):
if not self._items:
raise IndexError("pop from empty stack")
return self._items.pop()
def peek(self):
if not self._items:
raise IndexError("peek from empty stack")
return self._items[-1]
def __len__(self) -> int:
return len(self._items)
def __bool__(self) -> bool:
return bool(self._items)
What we got:
- The stack only has the methods a stack should have.
s.insert(),s.sort()giveAttributeError. The semantics are protected. - You can swap
listfordequeby changing one line. Users do not notice. - A clean boundary between API and implementation.
- Encapsulation is preserved.
Notice: code duplication is almost zero. len(self._items) is a single line. Composition is cheaper than it looks.
When inheritance is justified
It is not "never use inheritance". There are three situations where inheritance is the right tool.
1. Implementing an interface through ABC
This is legitimate inheritance. You explicitly say "I implement this contract".
class Notifier(ABC):
@abstractmethod
def send(self, msg: str) -> None: ...
class EmailNotifier(Notifier): # ← legitimate inheritance
def send(self, msg: str) -> None: ...
This is not "inheriting behaviour", it is "committing to fulfil the contract". If you pick Protocol over ABC, you do not need inheritance at all.
2. Template Method in a framework
The base class defines the algorithm, the children implement the steps:
class ReportGenerator(ABC):
def generate(self) -> str:
data = self._load()
return self._format(data)
@abstractmethod
def _load(self) -> list[dict]: ...
@abstractmethod
def _format(self, data: list[dict]) -> str: ...
class SalesReport(ReportGenerator):
def _load(self): return db.query(...)
def _format(self, data): return ...
Inheritance is right here because:
- The algorithm is shared and fixed.
- The extension points are explicitly designed (
@abstractmethod). - The subclass cannot break the base algorithm (it does not touch
generate).
Even so, there is an alternative through composition with strategies — the Strategy pattern.
3. Extending a framework that is built for inheritance
Django views, Tkinter widgets, PyTorch modules — their architects intentionally designed them to be inherited. The documentation says "inherit from View and override dispatch()". That is a different game.
class MyView(View): # Django requires it
def get(self, request):
return HttpResponse("Hi")
When inheritance is almost always a mistake
-
The child cannot fulfil the parent's full contract.
class Bird: def fly(self): ... class Penguin(Bird): def fly(self): raise NotImplementedError # penguins do not flyA classic LSP violation. If
Penguinis aBird, you should be able to use it wherever aBirdis expected. ButPenguin.fly()crashes. The contract is broken.Composition fix:
flying: Optional[FlyingBehavior]. A penguin hasNone, an eagle hasWingFlying(). -
The child wants to "steal" a few methods.
class Logger: def log(self, msg): ... class OrderProcessor(Logger): # ← we want self.log(...) ...OrderProcessoris not aLogger. It uses a logger. Composition:self._logger = logger. -
Multiple inheritance from two concrete classes.
class FileReader: ... class FileWriter: ... class FileReaderWriter(FileReader, FileWriter): ... # ← MRO nightmareComposition:
FileReaderWriterhas areaderfield and awriterfield. Clear, predictable, no MRO magic.
Python specifics: super() and MRO
How super() works
super() with no arguments (Python 3+) finds the next class in the MRO and calls its method with the same name.
class A:
def greet(self): print("A")
class B(A):
def greet(self):
super().greet() # → A.greet()
print("B")
B().greet()
# A
# B
MRO — Method Resolution Order
For multiple inheritance, Python builds the method lookup order with the C3 linearisation algorithm:
class A:
def method(self): print("A")
class B(A):
def method(self):
super().method()
print("B")
class C(A):
def method(self):
super().method()
print("C")
class D(B, C):
def method(self):
super().method()
print("D")
D().method()
print(D.__mro__)
Output:
A
C
B
D
(<class 'D'>, <class 'B'>, <class 'C'>, <class 'A'>, <class 'object'>)
Do you understand why, without looking at the source? If not, that is the argument against multiple inheritance. Every reader of your code will have to think about MRO.
Rule: if you need to look at
__mro__to know which method is being called, the design is wrong.
Mixins: legitimate multiple inheritance
A mixin is a class designed only to be mixed into other classes. It:
- Has no meaning on its own.
- Adds one narrow capability.
- Has no
__init__of its own (or a very simple one). - Does not depend on a specific parent type (it works with anything).
class TimestampedMixin:
"""Adds created_at / updated_at to a model."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.created_at = datetime.now()
self.updated_at = self.created_at
def touch(self):
self.updated_at = datetime.now()
class JSONSerializableMixin:
"""Adds to_json()."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def to_json(self) -> str:
return json.dumps(self.__dict__, default=str)
class User(TimestampedMixin, JSONSerializableMixin):
def __init__(self, name: str):
super().__init__()
self.name = name
This is an acceptable form of multiple inheritance because the mixins are orthogonal and do not collide. Django Class-Based Views and DRF are built on mixins.
Mixin rules:
- The name ends with
Mixin(convention). - One mixin = one capability.
Mixin()on its own should not make sense.- Always call
super().__init__(*args, **kwargs)so the chain does not break.
Composition with delegation: a Python pattern
If you want to expose almost all of an inner object's interface but protect your class from inheritance:
class TimestampedList:
def __init__(self):
self._items: list = []
self.modified_at = datetime.now()
def append(self, item):
self._items.append(item)
self.modified_at = datetime.now()
def __getitem__(self, i): # ← delegate indexing
return self._items[i]
def __len__(self): # ← delegate len()
return len(self._items)
def __iter__(self): # ← delegate iteration
return iter(self._items)
It looks almost like a list, but we control what is allowed. It is not "a list with extras", it is a separate class that uses a list.
Anti-patterns
1. Inheritance for code, not for the contract
class HttpClient:
def get(self, url): ...
def post(self, url, data): ...
class UserAPI(HttpClient): # ← UserAPI is not an "HttpClient", it is a client of one
def get_user(self, id):
return self.get(f"/users/{id}")
Right:
class UserAPI:
def __init__(self, http: HttpClient):
self._http = http
def get_user(self, id):
return self._http.get(f"/users/{id}")
2. Deep hierarchy (more than 2 levels)
class Vehicle: ...
class LandVehicle(Vehicle): ...
class Car(LandVehicle): ...
class SportsCar(Car): ...
class Ferrari(SportsCar): ...
Five levels are impossible to maintain. A change at Vehicle ripples through four layers below.
Rule: if your inheritance hierarchy is deeper than two levels, suspect a problem. Deeper than three is definitely a problem.
3. "Override + super() + some hack"
class A:
def process(self, x):
return x * 2
class B(A):
def process(self, x):
result = super().process(x)
return result if result > 10 else None # ← changed both the type and the contract
A.process returns int. B.process returns int | None. A caller that expects an A gets a surprise. This is an LSP violation, dressed up as "extension".
4. Multiple inheritance for two orthogonal capabilities instead of mixins
class Notifier: ...
class Logger: ...
class OrderProcessor(Notifier, Logger): ...
Here OrderProcessor is not a Notifier, not a Logger. It uses them. Composition:
class OrderProcessor:
def __init__(self, notifier: Notifier, logger: Logger):
self._notifier = notifier
self._logger = logger
Rules of thumb
- "Has-a" beats "is-a" as the first instinct. Ask: "is X a Y?". If it sounds weird, do not inherit.
- If the subclass cannot fulfil the full parent contract, do not inherit. That is an LSP signal.
- Inheritance hierarchy ≤ 2 levels (parent + child). Deeper means rework.
- Multiple inheritance is for mixins with a narrow responsibility.
super()with no arguments is the default.super(Cls, self)only for very specific cases.- If you need
__mro__to understand the code, rework the design. - Composition + Protocol = idiomatic Python. You will use this combo in 95% of cases.
- Template Method in a framework is fine. Everything else with ABC is suspicious.
One-line summary
When in doubt between inheritance and composition, choose composition. Inheritance is the right tool only for rare cases: implementing an ABC or Protocol, template method in a framework, mixins. Everything else is
self._x = xand a method call.