By WebNest Studio Engineering Team
Python Tutorial
Composition vs Inheritance
Inheritance models an "is-a" relationship: a SavingsAccount is a BankAccount. Composition models a "has-a" relationship: a Car has an Engine, an Order has a PaymentMethod. Experienced developers follow the guideline "favour composition over inheritance", because composed objects are easier to change, test and reuse.
This lesson compares the two approaches, shows the problems of deep inheritance, and demonstrates composition, delegation and dependency injection in Python.
Why it matters
Inheritance is the first tool people reach for, and deep class hierarchies are one of the main reasons code becomes hard to change. Building an object out of other objects is usually more flexible, and passing those parts in from outside is what makes code testable. "Favour composition over inheritance" is advice you will hear throughout your career.
Problems with Overusing Inheritance
Inheritance couples a child tightly to its parent's implementation: changes in the parent ripple into every subclass. Trying to express every combination through subclasses causes an explosion of classes (EmailUrgentNotifier, SmsUrgentNotifier...). Deep hierarchies are hard to follow, and a subclass inherits everything, even behaviour it should not have.
Composition
With composition, an object holds references to other objects and delegates work to them. Behaviour can be swapped at runtime by passing a different component, each component is small and testable on its own, and combinations are formed by assembling objects instead of defining new classes.
Dependency Injection
Passing collaborators into a class (usually through __init__) instead of creating them inside is called dependency injection. It lets tests pass fakes — a fake mailer instead of a real SMTP connection — and makes dependencies explicit. Frameworks such as FastAPI and Spring build on this idea.
When Inheritance Is Right
Use inheritance when there is a genuine is-a relationship, the subclass can be used anywhere the parent is expected (the Liskov substitution principle), and you want to share an interface or template. Use composition for everything else.
Examples
Composition: a Car has an Engine
class Engine:
def __init__(self, horsepower):
self.horsepower = horsepower
def start(self):
return f"{self.horsepower}hp engine started"
class ElectricMotor:
def start(self):
return "silent electric motor started"
class Car:
def __init__(self, model, engine):
self.model = model
self.engine = engine # has-a
def drive(self):
return f"{self.model}: {self.engine.start()}"
print(Car("Sedan", Engine(120)).drive())
print(Car("EV", ElectricMotor()).drive())
Sedan: 120hp engine started
EV: silent electric motor started
Avoiding a class explosion by composing behaviours
class EmailChannel:
def send(self, text):
return f"[email] {text}"
class SmsChannel:
def send(self, text):
return f"[sms] {text}"
class UrgentFormat:
def format(self, text):
return f"URGENT: {text.upper()}"
class PlainFormat:
def format(self, text):
return text
class Notifier:
def __init__(self, channel, formatter):
self.channel, self.formatter = channel, formatter
def notify(self, text):
return self.channel.send(self.formatter.format(text))
combos = [(EmailChannel(), PlainFormat()), (SmsChannel(), UrgentFormat()), (EmailChannel(), UrgentFormat())]
for channel, fmt in combos:
print(Notifier(channel, fmt).notify("server restarted"))
[email] server restarted
[sms] URGENT: SERVER RESTARTED
[email] URGENT: SERVER RESTARTED
Dependency injection makes testing easy
class SmtpMailer:
def send(self, to, body):
raise RuntimeError("would contact a real mail server")
class FakeMailer:
def __init__(self):
self.sent = []
def send(self, to, body):
self.sent.append((to, body))
class RegistrationService:
def __init__(self, mailer):
self.mailer = mailer # injected dependency
def register(self, email):
self.mailer.send(email, "Welcome to Webnest!")
return f"registered {email}"
fake = FakeMailer()
service = RegistrationService(fake)
print(service.register("asha@webnest.in"))
print(fake.sent)
registered asha@webnest.in
[('asha@webnest.in', 'Welcome to Webnest!')]
Common Mistakes
- Using inheritance just to reuse a helper method.
- Creating a subclass for every combination of features.
- Creating dependencies inside __init__ (self.mailer = SmtpMailer()), making classes hard to test.
- Subclasses that break the parent's contract, so they cannot replace it safely.
Exercise
Write a Car class that is given an engine object when it is created and delegates to it. The same Car class must work with either kind of engine.
Expected output: Petrol engine started then Electric motor started
class PetrolEngine:
def start(self):
return "Petrol engine started"
class ElectricEngine:
def start(self):
return "Electric motor started"
class Car:
# TODO: accept an engine in __init__ and store it
# TODO: start() should return whatever the engine's start() returns
pass
print(Car(PetrolEngine()).start())
print(Car(ElectricEngine()).start())
Show hints
- The car has an engine; it is not a kind of engine, so no inheritance is needed.
- Calling a method on the stored object and returning its result is called delegation.
Show solution
class PetrolEngine:
def start(self):
return "Petrol engine started"
class ElectricEngine:
def start(self):
return "Electric motor started"
class Car:
def __init__(self, engine):
self.engine = engine
def start(self):
return self.engine.start()
print(Car(PetrolEngine()).start())
print(Car(ElectricEngine()).start())
Quick quiz
1. Which relationship does composition express?
- A. has-a
- B. is-a
- C. equals
- D. inherits
Show answer
A. A car has an engine. Inheritance expresses is-a: a manager is an employee.
2. What is dependency injection?
- A. Installing packages with pip
- B. Giving an object the things it needs from outside, usually through its constructor
- C. Importing a module inside a function
- D. Calling super()
Show answer
B. The object does not create its own dependencies, so they can be replaced.
3. Why does dependency injection make testing easier?
- A. The tests run faster
- B. No tests are needed
- C. A fake object can be passed in place of a real database or email service
- D. It removes the need for classes
Show answer
C. The test controls what the object talks to.
Interview questions
What does "favour composition over inheritance" mean?
Show answer
Build behaviour by combining small objects, each with one job, in preference to creating deep hierarchies of subclasses. Inheritance ties a subclass closely to its parent: a change in the parent can break every subclass, and combining features requires a new subclass for each combination. With composition, parts can be swapped, reused in other classes and replaced with fakes in tests.
When is inheritance the right choice?
Show answer
When there is a true is-a relationship and the subclass can be used anywhere the parent is expected, and when a framework is designed for it, as with exceptions, Django models or abstract base classes that define a contract. A shallow hierarchy with a stable parent is fine; inheriting only to reuse a few methods is usually a sign that composition would be better.
Key Points to Remember
- Inheritance = is-a; composition = has-a.
- Favour composition: smaller, swappable, testable components.
- Compose behaviours instead of creating a subclass per combination.
- Inject dependencies through __init__ to decouple and test easily.
- Use inheritance for genuine is-a relationships that honour the parent's contract.
Practice in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering