Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 09 / Topic 11 of 12

Composition vs inheritance

  • Inheritance = "is-a": a Manager is an Employee.
  • Composition = "has-a": a Car has an Engine. One object keeps another object as an attribute and uses it.

Think of a laptop: it has a battery. You can swap the battery without the laptop "being" a battery.

Real-world example: a car with a swappable engine.

class PetrolEngine:
    def start(self) -> str:
        return "Vroom (petrol)"

class ElectricMotor:
    def start(self) -> str:
        return "Hmm (electric)"

class Car:
    def __init__(self, model: str, engine):
        self.model = model
        self.engine = engine             # composition: a Car HAS an engine

    def drive(self) -> str:
        return f"{self.model}: {self.engine.start()}"   # hand the work to the engine

print(Car("City Hatch", PetrolEngine()).drive())   # City Hatch: Vroom (petrol)
print(Car("Eco Hatch", ElectricMotor()).drive())   # Eco Hatch: Hmm (electric)

With inheritance you would need PetrolCar, ElectricCar, PetrolSUV, ElectricSUV, and so on. With composition you mix and match parts.

Inheritance Composition
Relationship is-a has-a
Example SavingsAccount(Account) Car has an Engine
Link Fixed when you write the class Can be changed when the program runs
Use when The child really is a special kind of the parent You want to combine parts

Rule of thumb: prefer composition; use inheritance only when "is-a" is clearly true.

๐Ÿ” Going deeper: passing the engine into __init__ (instead of creating it inside) is called dependency injection. It makes classes easy to test, as Part 11 shows.

Done here? The practice set for Part 9 โ€” 8 exercises with solutions โ€” is on the part page.

Search the guide