Course contentsShow
← Python
Lesson 480 of 1,0607. Object-Oriented ProgrammingFree lesson

Implementing Composition Over Inheritance

Learn to design flexible systems by assembling complex objects from smaller, independent components instead of relying on deep inheritance hierarchies.

Implementing Composition Over Inheritance

In this lesson, you will learn how to design more flexible Python systems by assembling complex objects from smaller, independent components rather than forcing them into rigid, deep inheritance hierarchies.

The Problem with Deep Inheritance

Inheritance ("is-a" relationship) is often misused to share code, leading to the "Fragile Base Class" problem. If you have a Bird class and decide to inherit Penguin from it, you might accidentally give your penguin a fly() method, which you then have to override to raise an error. As your system grows, these hierarchies become difficult to reason about and hard to refactor.

The Composition Alternative

Composition ("has-a" relationship) involves building objects by combining distinct, specialized objects. Instead of inheriting behavior, your class delegates tasks to "component" objects that it holds as attributes.

Consider a robot system. Instead of creating a massive Robot hierarchy, you can compose a robot from smaller, swappable components:

class Battery:
    def get_power(self):
        return "100% charge"

class MovementSystem:
    def move(self):
        return "Moving on treads"

class Robot:
    def __init__(self):
        # Composition: The robot 'has' a battery and a movement system
        self.battery = Battery()
        self.mover = MovementSystem()

    def status(self):
        return f"Power: {self.battery.get_power()}, State: {self.mover.move()}"

my_robot = Robot()
print(my_robot.status())

Why This Works

Composition makes your code modular. If you need a robot that flies, you don't need a FlyingRobot subclass; you simply swap the MovementSystem instance for a FlightSystem instance at runtime. This "pluggability" is significantly easier to maintain than managing an inheritance tree where adding one feature might break three other subclasses. By delegating functionality to small, focused objects, you keep each part of your system loosely coupled and highly reusable.

Key Takeaway: Prefer composition to build flexible objects by delegating responsibilities to independent components, avoiding the complexity and rigidity inherent in deep inheritance chains.