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 speaksHere: 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 → Employee2️⃣ 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 startedHere: 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 |
|
|
Tighter relationship | More loosely coupled |
Simple rule:
If you are thinking "is a" → inheritance.
If you are thinking "has a" → composition.