Skip to content

Module 11 · Object-Oriented Programming — topic 25 of 25

Composition

Building objects from other objects: the has-a relationship, delegating work to parts, swapping components (dependency injection), and why composition is often preferred over inheritance.

Beginner 10 min read·Lesson 182 of 306 in Python Programming

Learning objectives

  • Build classes from smaller component objects
  • Delegate behaviour to components
  • Choose between composition and inheritance

Definition

Composition is a design where an object contains other objects as attributes and delegates work to them. It models has-a relationships: a Car has an Engine, a Library has Books.

Introduction

A car is not a kind of engine; it has an engine. Composition puts an Engine object inside the Car and lets the car ask the engine to do engine things.

Why it matters

Composition gives flexible designs. Parts can be replaced, tested separately and reused, without the tight coupling and deep hierarchies that inheritance can create.

Detailed explanation

To compose, store component objects in attributes: self.engine = Engine(hp).

Delegation means the outer object's method calls the component: def start(self): return self.engine.start().

Passing components into __init__ instead of creating them inside (dependency injection) lets you swap parts — for example a fake notifier in tests.

Rule of thumb: inheritance for is-a, composition for has-a. When unsure, composition is usually the safer choice ('favour composition over inheritance').

Composition and inheritance work together: a class can inherit from one base and also contain several components.

In strict composition a part's life is tied to its owner; in aggregation parts exist independently (members can leave a library). Python code looks the same either way.

Syntax

Python
class Engine:
def start(self):
return "engine started"
class Car:
def __init__(self):
self.engine = Engine() # Car has an Engine
def start(self):
return self.engine.start() # delegation
  • Store parts as attributes.
  • Delegate work to the parts.
  • Pass parts in to make them swappable.

Code examples

A car has an engine

Python
class Engine:
def __init__(self, hp):
self.hp = hp
def start(self):
return f"{self.hp} hp engine started"
class Car:
def __init__(self, model, hp):
self.model = model
self.engine = Engine(hp)
def start(self):
return f"{self.model}: {self.engine.start()}"
print(Car("Nexon", 118).start())
Output
Nexon: 118 hp engine started

Swapping a component

Python
class ConsoleNotifier:
def send(self, msg):
return f"console: {msg}"
class ListNotifier:
def __init__(self):
self.sent = []
def send(self, msg):
self.sent.append(msg)
return f"stored ({len(self.sent)})"
class OrderService:
def __init__(self, notifier):
self.notifier = notifier
def place(self, item):
return self.notifier.send(f"order placed: {item}")
print(OrderService(ConsoleNotifier()).place("book"))
fake = ListNotifier()
svc = OrderService(fake)
svc.place("pen")
print(svc.place("bag"), fake.sent)
Output
console: order placed: book
stored (2) ['order placed: pen', 'order placed: bag']

More examples

A library built from parts

Python
class Book:
def __init__(self, title):
self.title = title
self.borrower = None
class Member:
def __init__(self, name):
self.name = name
self.books = []
class Library:
def __init__(self):
self.books = {}
self.members = {}
def add_book(self, title):
self.books[title] = Book(title)
def join(self, name):
self.members[name] = Member(name)
def lend(self, title, name):
book, member = self.books[title], self.members[name]
if book.borrower:
return f"{title} is with {book.borrower.name}"
book.borrower = member
member.books.append(book)
return f"{name} borrowed {title}"
def report(self):
return {t: (b.borrower.name if b.borrower else "-") for t, b in self.books.items()}
lib = Library()
for t in ["Dune", "Emma"]:
lib.add_book(t)
for n in ["Asha", "Ravi"]:
lib.join(n)
print(lib.lend("Dune", "Asha"))
print(lib.lend("Dune", "Ravi"))
print(lib.report())
Output
Asha borrowed Dune
Dune is with Asha
{'Dune': 'Asha', 'Emma': '-'}

Step-by-step explanation

  • Library has books and members; neither is a kind of library.
  • lend coordinates its parts: it checks the book, then updates both the book and the member.
  • report reads each component's state to build a summary.

Expected output

Running “A library built from parts” prints exactly:

TextOutput
Asha borrowed Dune
Dune is with Asha
{'Dune': 'Asha', 'Emma': '-'}

Practical applications

  • A web app object holds a database connection, a cache and a mailer.
  • Game entities composed of position, health and inventory components.

Best practices

  • Use composition for has-a relationships.
  • Inject components through __init__.
  • Keep each component focused on one job.

Common mistakes

Inheriting to reuse a part

Avoid

class Car(Engine): ...

Prefer

class Car:
def __init__(self):
self.engine = Engine()

A car is not an engine; inheritance would expose engine methods as car methods.

Hard-wiring dependencies

Avoid

def __init__(self):
self.notifier = EmailNotifier()

Prefer

def __init__(self, notifier):
self.notifier = notifier

Passing the part in makes it easy to swap and to test.

Important notes

  • This completes the OOP module; the next module covers exception handling, which uses class hierarchies heavily.

Key takeaways

  • Composition builds objects from other objects.
  • The outer object delegates to its parts.
  • Prefer composition unless there is a true is-a relationship.

Try it yourself

  1. 1
    Model a Computer composed of CPU, Memory and Storage objects with a specs() method.
  2. 2
    Rewrite a class that inherits from list into one that holds a list and delegates to it.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateA car has an engine. Which design models this best?
Practise this topic