Here’s a basic example of composition in Python:
Example: Car and Engine:
- [Composition] The Car class includes an Engine instance as part of its attributes, indicating a "has-a" relationship.
- [Behavior Delegation] The Car delegates the starting and stopping behavior to its Engine object.
- [Flexibility] You can swap the Engine object with another implementation without modifying the Car class, making the design more modular and flexible.
class Engine:
def __init__(self, horsepower):
self.horsepower = horsepower
def start(self):
print(f"Engine with {self.horsepower} HP started.")
def stop(self):
print(f"Engine with {self.horsepower} HP stopped.")
class Car:
def __init__(self, make, model, engine):
self.make = make
self.model = model
self.engine = engine # Composition: Car "has an" Engine
def start(self):
print(f"{self.make} {self.model} is starting...")
self.engine.start() # Delegating behavior to Engine
def stop(self):
print(f"{self.make} {self.model} is stopping...")
self.engine.stop() # Delegating behavior to Engine
# Create an Engine object
engine = Engine(horsepower=150)
# Create a Car object that has the Engine
car = Car(make="Toyota", model="Corolla", engine=engine)
# Use the Car and its Engine
car.start()
car.stop()