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
1# Program to demonstrate composition23class Engine:4 def start(self):5 print("Engine started")67class Car:8 def __init__(self):9 self.engine = Engine()1011 def drive(self):12 self.engine.start()13 print("Car is moving")1415c = 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.
After this program
If the idea is still fuzzy, read Day 11: Classes and Objects in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 object-oriented programs, or see every topic on Python exercises.