Introduction to Composition
Swipe to show menu
Composition represents a has-a relationship, where a class contains an instance of another class instead of inheriting from it. For example, a Car has an Engine. This differs from inheritance, which models an 'is-a' relationship, such as a Truck is a Vehicle.
1234567891011121314151617class Engine: def start(self): return "Engine started" class Car: def __init__(self, brand, engine): self.brand = brand self.engine = engine # Car HAS an Engine def drive(self): return f"{self.brand}: {self.engine.start()}" engine = Engine() car = Car("Toyota", engine) print(car.drive())
Car does not inherit from Engine. Instead, it contains an Engine object and uses it to perform its work. This shows a has-a relationship, not is-a, making the design more flexible and easier to change later.
You should use composition when you need flexible parts, clear boundaries, and runtime replacement of behavior. Prefer inheritance when a true is-a hierarchy is obvious and stable.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Introduction to Composition
Composition represents a has-a relationship, where a class contains an instance of another class instead of inheriting from it. For example, a Car has an Engine. This differs from inheritance, which models an 'is-a' relationship, such as a Truck is a Vehicle.
1234567891011121314151617class Engine: def start(self): return "Engine started" class Car: def __init__(self, brand, engine): self.brand = brand self.engine = engine # Car HAS an Engine def drive(self): return f"{self.brand}: {self.engine.start()}" engine = Engine() car = Car("Toyota", engine) print(car.drive())
Car does not inherit from Engine. Instead, it contains an Engine object and uses it to perform its work. This shows a has-a relationship, not is-a, making the design more flexible and easier to change later.
You should use composition when you need flexible parts, clear boundaries, and runtime replacement of behavior. Prefer inheritance when a true is-a hierarchy is obvious and stable.
Thanks for your feedback!