🐍 Lesson 4: Polymorphism
1. What is polymorphism?
In short → Polymorphism means the same method can be used across different classes, each with its own behavior.
In detail → Polymorphism means the same method name can be used in different classes, but each class can implement it differently.
2. Why Polymorphism?
- Code flexibility
- Reusability
- Makes code more abstract and general
- Real-world modeling (e.g., animals speak differently)
3. Summary
✅ Polymorphism = same method name, different behavior
✅ Works with inheritance (method overriding) or unrelated classes (duck typing)
✅ Python built-ins like len() are polymorphic
✅ Makes code flexible, reusable, and closer to real-world
python
# ===== 1. Example with Inheritance =====
class Animal:
def speak(self):
return "Some sound"
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
animals = [Dog(), Cat(), Animal()]
for a in animals:
print(a.speak())
# ===== 2. Built-in Polymorphism =====
print(f"\n===== Built-in Polymorphism =====")
print(f"len('Sai') = {len('Sai')}") # 3 (string length)
print(f"len([1,2,3,4]) = {len([1,2,3,4])}") # 4 (list length)
print(f"len({{'a':1,'b':2}}) = {len({'a':1,'b':2})}") # 2 (dict length)
# ===== 3. Method Overriding =====
class Vehicle:
def move(self):
return "Moving..."
class Car(Vehicle):
def move(self):
return "Driving on the road"
class Boat(Vehicle):
def move(self):
return "Sailing on water"
vehicles = [Car(), Boat()]
for v in vehicles:
print(v.move())You should see
Woof! Meow! Some sound ===== Built-in Polymorphism ===== len('Sai') = 3 len([1,2,3,4]) = 4 len({'a':1,'b':2}) = 2 Driving on the road Sailing on water