Composition Example in Python

Use composition by placing one object inside another to build complex behavior.

IntermediateObject-Oriented ProgramsExample 15 of 25
composition-example.py
Run in browser
1# Program to demonstrate composition
2
3class Engine:
4 def start(self):
5 print("Engine started")
6
7class Car:
8 def __init__(self):
9 self.engine = Engine()
10
11 def drive(self):
12 self.engine.start()
13 print("Car is moving")
14
15c = Car()
16c.drive()

Output

Engine started
Car is moving

What's going on

Car is composed of an Engine object; it delegates the 'start' behavior to Engine instead of inheriting from it.