Composition

Composition is a "has-a" relationship where one object ownsanother. The contained object is created inside the container — and if the container is destroyed, the contained object is too. This is called a strong has-arelationship.

has-a vs is-a

  • is-a → use inheritance: a Dog is an Animal
  • has-a → use composition: a Car has an Engine

A common OOP mistake is using inheritance when composition is correct. A Car should not inherit from Engine.

Composition in Code

class Engine:
    def __init__(self, hp):
        self.horsepower = hp
class Car:
    def __init__(self, make, hp):
        self.make   = make
        self.engine = Engine(hp)  # Car CREATES the Engine
    def get_power(self):
        return self.engine.horsepower
c = Car("Toyota", 400)
print(c.get_power())  # → 400
400

The Engine is created inside Car.__init__. It has no independent existence — this is the defining feature of composition.

Lifecycle Ownership

Composition = the container controls the lifetime of the contained object. When the Car is deleted, its Engine ceases to exist too (no other reference holds it).

  • Car → Engine (composition — filled diamond in UML)
  • House → Rooms (composition)
  • Computer → CPU (composition)

Your Task

  1. Write class Car: with __init__(self, make, horsepower)
  2. Inside __init__: store self.make = make and create self.engine = Engine(horsepower)
  3. Write get_power(self): return self.engine.horsepower
  4. Write __str__(self): return e.g. "Toyota (400hp)"
Section 1/4has-a vs is-a

has-a vs is-a

A common OOP mistake is using inheritance when composition is correct. A Car should not inherit from Engine.

Composition

Composition is a "has-a" relationship where one object ownsanother. The contained object is created inside the container — and if the container is destroyed, the contained object is too. This is called a strong has-arelationship.

has-a vs is-a

  • is-a → use inheritance: a Dog is an Animal
  • has-a → use composition: a Car has an Engine

A common OOP mistake is using inheritance when composition is correct. A Car should not inherit from Engine.

Output:

Click "Check" to run your code.