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.
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
- Store parts as attributes.
- Delegate work to the parts.
- Pass parts in to make them swappable.
Code examples
A car has an engine
Nexon: 118 hp engine started
Swapping a component
console: order placed: book stored (2) ['order placed: pen', 'order placed: bag']
More examples
A library built from parts
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:
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
Prefer
A car is not an engine; inheritance would expose engine methods as car methods.
Hard-wiring dependencies
Avoid
Prefer
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
- 1Model a Computer composed of CPU, Memory and Storage objects with a specs() method.
- 2Rewrite 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?