Composition and inheritance are the two ways to combine a class with other behaviour, and choosing wrongly is one of the more expensive mistakes in object-oriented design. Inheritance says "this class is a that class". Composition says "this class has a that class". The second one is far more flexible, and in most real code it is the one that you want.
The previous lesson in this module covered "Properties: Getters, Setters and Validation", and this lesson is the last one in the Advanced OOP in Python module.
Both approaches produce working code. The difference shows up later, when the requirements change. Inheritance ties you to a parent that you cannot easily swap, while composition holds a collaborator that you can replace at any time, even while the program is running.
How do you tell is-a from has-a?
Finish the sentence "a Car is a ..." with something that would still make sense if you swapped one for the other. "A car is a vehicle" passes, so inheriting from Vehicle is reasonable. "A car is an engine" does not pass, so a car should have an engine, and you should store it as an attribute.
The same test catches the classic mistakes. A FileWriter is not a Log, so it should not inherit from one. A database session is not a repository, even though it can fetch things for you. And a User is not a dict just because both of them hold key and value data.
class Vehicle:
def __init__(self, wheels):
self.wheels = wheels
def describe(self):
return 'a vehicle with ' + str(self.wheels) + ' wheels'
class Engine:
def __init__(self, horsepower):
self.horsepower = horsepower
def start(self):
return 'engine running at ' + str(self.horsepower) + 'hp'
class Car(Vehicle):
def __init__(self, engine):
super().__init__(wheels=4)
self.engine = engine
def describe(self):
return super().describe() + ' and ' + self.engine.start()
print(Car(Engine(120)).describe())
Here Car inherits from Vehicle because the substitution holds, and it holds an Engine as an attribute because the substitution does not. That is the shape you want. Use inheritance for what a thing genuinely is, and use composition for what it uses.
What does a composition-based version look like?
The same car, written with composition, takes its engine as an argument when it is built. The car no longer knows how the engine works. It only knows the interface that it expects.
class Engine:
def __init__(self, label):
self.label = label
def start(self):
return self.label + ' engine running'
class Car:
def __init__(self, engine):
self.engine = engine
def drive(self):
return self.engine.start() + ', wheels turning'
print(Car(Engine('petrol')).drive())
Notice what changed. The Car class now has a single job, which is to put the parts it holds to work together. The engine is a separate object with its own tests. If you later need an electric engine with a different interface, you write one more class and pass it in, and the Car code does not change at all.
Why is composition easier to change, and easier to test?
Because the collaborator is a value that you pass in, and not a parent that is fixed inside the class. Swapping it is just an assignment.
class Engine:
def __init__(self, label):
self.label = label
def start(self):
return self.label + ' engine running'
class ElectricMotor:
def __init__(self, kilowatts):
self.kilowatts = kilowatts
def start(self):
return 'electric motor at ' + str(self.kilowatts) + 'kW'
class Car:
def __init__(self, engine):
self.engine = engine
def drive(self):
return self.engine.start() + ', wheels turning'
my_car = Car(Engine('petrol'))
print(my_car.drive())
my_car.engine = ElectricMotor(100)
print(my_car.drive())
print('the class of the car never changed:', type(my_car).__name__)
Try to do the same thing with inheritance. You would need a new class, ElectricCar(Vehicle), that duplicates or overrides the behaviour of Car, and any code that checks isinstance(car, Car) would now be wrong. With composition, the type of the car did not change at all. Only what is inside it changed.
That property is what makes composition the better default whenever a second implementation might be needed one day. Logging instead of real output, a real database instead of an in-memory one, and a real payment gateway instead of a fake one in tests are all the same shape of problem.
The testing benefit follows from the same design. Because the dependency is explicit and you can inject it, a test can supply a stub that records what it was asked to do, without patching anything globally and without reaching into the internals of the class.
class RecordingSender:
def __init__(self):
self.sent = []
def send(self, message):
self.sent.append(message)
return 'sent'
class Notifier:
def __init__(self, sender):
self.sender = sender
def notify(self, message):
return self.sender.send(message) + ': ' + message
stub = RecordingSender()
notifier = Notifier(stub)
print(notifier.notify('disk almost full'))
print('the stub recorded:', stub.sent)
With inheritance, testing usually means subclassing the class that you are testing and overriding the part that you do not want to run. That is awkward when the part is buried several levels deep, and it is impossible when the part is created inside a method instead of being passed in. Composition turns that difficulty into one constructor argument.
This is the strongest practical argument for composition. Tests that need no mocking frameworks, no monkey-patching, and no global state tend to be tests that people actually write.
When is inheritance still the right choice?
Three situations justify it. The first is mixins, which are small classes that add behaviour to a family of classes without carrying any state, exactly as the previous lesson built them. The second is protocols and abstract base classes, where you want to state a contract that several unrelated classes must satisfy, usually with abc.ABC and @abstractmethod. The third is genuine is-a taxonomies that will never need a second implementation, such as a Dog and a Cat that both have a Pet base class with shared and stable behaviour.
| Situation | Reach for | Why |
|---|---|---|
| the object has a collaborator | composition | the collaborator can be swapped or stubbed |
| you want a shared base with no state | inheritance, as a mixin | it adds behaviour to many classes at once |
| you want to enforce a contract | inheritance, as an ABC | the base declares what must exist |
| the object really is a kind of something | inheritance | the is-a substitution reads naturally |
Notice that in every inheritance case above, the base class either carries no state or states a contract. Those are the situations where inheritance stays safe. A base class that carries mutable attributes which the subclasses are expected to share is the fragile case, and composition sidesteps it completely.
Is there a third option?
Often there is, and it is neither of them. Python does not ask you to declare that a class implements anything. If your code only calls engine.start(), then anything with a start() method will do, and you never have to inherit from a common base to satisfy anybody.
def start_anything(engine):
return engine.start()
class PetrolEngine:
def start(self):
return 'petrol engine running'
class ElectricMotor:
def start(self):
return 'electric motor running'
print(start_anything(PetrolEngine()))
print(start_anything(ElectricMotor()))
This is duck typing, where the type of an object is decided by what it can do and not by what it declares. It fits naturally with composition. You hold a collaborator, and the only requirement is that it answers the methods that you call.
The downside is that the failure happens later, at the point of use, instead of at the moment the object is built. An abstract base class trades some of that flexibility for an earlier and clearer error. Many codebases use both, with duck typing at the edges and abstract bases in the core.
The decision rule
- Inheritance models is-a and composition models has-a. Misidentifying the relationship is the root mistake.
- Composition holds a collaborator that you can swap at runtime, while inheritance fixes the parent in permanently.
- Injecting dependencies makes them easy to stub in tests.
- Inheritance earns its place for mixins, abstract base classes, and stable taxonomies.
- When you are in doubt, prefer composition and let duck typing handle the rest.
Try it yourself: refactor one inheritance into composition
Take a class of your own that inherits from another, and list its inherited methods one by one. For each one, ask whether the subclass genuinely is that kind of thing, or whether it merely uses the parent's capability. Most of the time the answer splits the inherited methods into two groups.
Move the second group into a collaborator that you pass to the constructor, and delete the inheritance. Write a test that supplies a recording stub in place of the real collaborator and checks what was called. Finally, write a second implementation of that collaborator, one fake for tests and one real for production, and switch between them at the call site without changing the class that uses it.