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 browser1# 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.