Python Mastery – From Basics to Brilliance / Object-Oriented Programming (OOP)

Composition vs Inheritance

1️⃣ Inheritance — "IS-A"

Inheritance means one class inherits features from another class.

class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    pass

dog = Dog()
dog.speak() #Animal speaks

Here: Dog IS-A Animal

Dog gets the methods of Animal.

🧠 Use inheritance when:

There is a clear "is-a" relationship.

Examples:

Dog → Animal
Car → Vehicle
Manager → Employee

2️⃣ Composition — "HAS-A"

Composition means a class contains an object of another class.

class Engine:
    def start(self):
        print("Engine started")

class Car:
    def __init__(self):
        self.engine = Engine()

    def start(self):
        self.engine.start()

car = Car()
car.start() #Engine started

Here: Car HAS-A Engine. The Car uses an Engine rather than inheriting from it.

🧠 Use composition when:

One object has or uses another object.

Examples:

Car → Engine
Computer → CPU
House → Room

⚖️ Quick Comparison

Inheritance 🧬

Composition 🧩

IS-A relationship

HAS-A relationship

Child inherits from parent

Class contains another object

Promotes inheritance/reuse

Promotes flexibility/reuse

class Dog(Animal)

self.engine = Engine()

Tighter relationship

More loosely coupled

Simple rule:

If you are thinking "is a" → inheritance.
If you are thinking "has a" → composition.