Inheritance versus composition
Course contents (15 lessons)
- Iteration the Python way
- List, dict and set comprehensions
- Iterators and generators
- Functions as building blocks
- Closures and decorators
- Context managers and the with statement
- Object-oriented Python in depth
- Classes and dataclasses
- Properties and special (dunder) methods
- Inheritance versus composition
- Quality: types, packaging and tests
- Type hints and mypy
- Packaging a project with pyproject.toml
- Testing with pytest
- Async code and web APIs
- async and await with asyncio
- Working with HTTP APIs and JSON
- Performance, concurrency and a final project
- Performance and profiling
- Concurrency: threads versus processes
- Final project: a price tracker command-line tool
Two ways to reuse code
When one class needs the abilities of another, you have two choices. Inheritance says "a B is a kind of A". Composition says "a B has an A" and uses it. Both are valid. The trouble is that beginners reach for inheritance first, and it can lead to tangled designs.
Inheritance basics
class Employee:
def __init__(self, name, base_salary):
self.name = name
self.base_salary = base_salary
def monthly_pay(self):
return self.base_salary
class Manager(Employee):
def __init__(self, name, base_salary, bonus):
super().__init__(name, base_salary) # run the parent's setup
self.bonus = bonus
def monthly_pay(self): # override
return super().monthly_pay() + self.bonus
print(Manager("Sara", 150_000, 30_000).monthly_pay()) # 180000
The child class gets everything from the parent and can add or override behaviour. super() gives access to the parent's version. Forgetting to call super().__init__() is the classic mistake: the parent's attributes are never created and you get an AttributeError later, far from the cause.
Abstract base classes
Sometimes a parent exists only to define a shape that children must fill in. Use the abc module so that Python refuses to create an incomplete child.
from abc import ABC, abstractmethod
from dataclasses import dataclass
class PaymentMethod(ABC):
@abstractmethod
def charge(self, amount: float) -> str:
"""Charge the amount and return a receipt id."""
class CardPayment(PaymentMethod):
def __init__(self, card_number: str):
self.card_number = card_number
def charge(self, amount: float) -> str:
return f"CARD-{self.card_number[-4:]}-{amount:.0f}"
class CashPayment(PaymentMethod):
def charge(self, amount: float) -> str:
return f"CASH-{amount:.0f}"
@dataclass
class Checkout:
payment: PaymentMethod # composition: a Checkout HAS a payment method
def pay(self, amount: float) -> str:
if amount <= 0:
raise ValueError("amount must be positive")
return self.payment.charge(amount)
print(Checkout(CardPayment("4111111111111111")).pay(2500)) # CARD-1111-2500
print(Checkout(CashPayment()).pay(800)) # CASH-800
# PaymentMethod() # TypeError: can't instantiate abstract class
Where the design shows its shape
PaymentMethod defines the contract: anything that can charge. CardPayment and CashPayment fulfil it. Checkout does not inherit from any of them. It holds one, so it works with any payment method, present or future, without changes. Adding a wallet payment later means writing one new class, and nothing else is touched.
The problem with deep hierarchies
Imagine Employee to Manager to RemoteManager to RemoteManagerWithEquity. Each level makes the previous one harder to change, because every child depends on the parent's details. This is called tight coupling. A change in Employee may break classes three levels down. A common guideline is "favour composition over inheritance": build objects from smaller parts with one job each, rather than stacking up class trees.
Duck typing and Protocols
Python does not require inheritance to share an interface. If an object has a charge method, it works in Checkout whether or not it inherits anything. This is called duck typing: if it quacks like a duck, it is a duck. For type checkers you can describe the shape with typing.Protocol:
from typing import Protocol
class Chargeable(Protocol):
def charge(self, amount: float) -> str: ...
Any class with a matching charge method satisfies it without inheriting. We come back to protocols in the typing lesson.
Multiple inheritance and the MRO
Python allows several parents. The order in which Python searches them is the method resolution order (MRO), visible as ClassName.__mro__. The cooperative super() follows this order. Multiple inheritance is mostly used for small mixins, classes that add one narrow feature such as logging or JSON conversion, with no state of their own. Do not build complex trees with it. If you need to read the MRO to understand your own code, simplify it.
How I choose
- Use inheritance when there is a true "is a" relationship, the child can be used anywhere the parent is expected, and you control both classes.
- Use composition when you want to reuse behaviour, when the relationship is "has a" or "uses a", or when behaviour should be swapped at run time.
- Use a function when there is no state. Python does not force everything into a class.
- Do not inherit from built-in containers like
listordictjust to add a feature. Their methods do not always call each other as you expect. Hold a list inside your class instead.
Common mistakes
- Inheriting for code reuse only. A
Stackclass that inherits fromlistexposesinsertandsort, which break the idea of a stack. - Overriding a method with a different signature. Callers that expect the parent's version fail.
- Deep trees. More than two or three levels is a warning sign.
Try it yourself
Design a small notification system. Create an abstract Notifier with send(to, message), then EmailNotifier and SmsNotifier that just print what they would send. Write an OrderService class that receives a notifier in its constructor and calls it when an order is placed. Then add a LoggingNotifier that wraps another notifier and logs before delegating to it. That wrapper is composition in action.
from abc import ABC, abstractmethod
from dataclasses import dataclass
class PaymentMethod(ABC):
@abstractmethod
def charge(self, amount: float) -> str:
"""Charge the amount and return a receipt id."""
class CardPayment(PaymentMethod):
def __init__(self, card_number: str):
self.card_number = card_number
def charge(self, amount: float) -> str:
return f"CARD-{self.card_number[-4:]}-{amount:.0f}"
class CashPayment(PaymentMethod):
def charge(self, amount: float) -> str:
return f"CASH-{amount:.0f}"
@dataclass
class Checkout:
payment: PaymentMethod # composition: a Checkout HAS a payment method
def pay(self, amount: float) -> str:
if amount <= 0:
raise ValueError("amount must be positive")
return self.payment.charge(amount)
print(Checkout(CardPayment("4111111111111111")).pay(2500)) # CARD-1111-2500
print(Checkout(CashPayment()).pay(800)) # CASH-800
# PaymentMethod() # TypeError: can't instantiate abstract class
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account