One interface, many implementations
Day 60 of 149
👉 Full deep-dive with code examples
The Universal Remote Analogy
One remote controls many devices:
- Press "Play" → TV plays video
- Press "Play" → Music player plays audio
- Press "Play" → Game console starts game
Same button, different behaviors!
The remote doesn't care WHAT device - just that it responds to "Play".
How Polymorphism Works
class Cat:
def speak(self):
return "Meow!"
class Dog:
def speak(self):
return "Woof!"
class Cow:
def speak(self):
return "Moo!"
# Same interface, different behavior!
animals = [Cat(), Dog(), Cow()]
for animal in animals:
print(animal.speak())
# Output:
# Meow!
# Woof!
# Moo!
We call .speak() without knowing the specific animal type!
Why It's Powerful
Without polymorphism:
if isinstance(animal, Cat):
animal.meow()
elif isinstance(animal, Dog):
animal.bark()
elif isinstance(animal, Cow):
animal.moo()
# Ugly! And breaks when you add new animals
With polymorphism:
animal.speak() # Just works!
# Add new animal? Just implement speak()!
The Real Power
Add new types without changing existing code!
class Robot:
def speak(self):
return "Beep boop!"
# Works immediately with all existing code!
In One Sentence
Polymorphism lets different objects respond to the same method call in their own unique way.
🔗 Enjoying these? Follow for daily ELI5 explanations!
Making complex tech concepts simple, one day at a time.
Top comments (0)