Problem Statement
When would you prefer composition over inheritance in Python?
Explanation
Choose composition when you want to build complex behavior by combining smaller parts, and the relationship is “has a” rather than “is a”. This avoids deep hierarchies and the fragility that comes from tight coupling to a base class.
Composition makes testing easier and lets you swap components without changing public APIs. Inheritance is still useful for true specialization, but composition keeps designs flexible and easier to evolve.
Code Solution
SolutionRead Only
class Engine:
def start(self): return 'start'
class Car:
def __init__(self, engine): self.engine=engine
def go(self): return self.engine.start()