One handle, many heads
Polymorphism as a Multi-tool
The analogy
You shout "make a sound!" at a dog, a cat and a car. All three understand the instruction; you get a bark, a meow and a honk. You did not need to know what you were talking to — one instruction, many behaviours.
Visualizer
One message, many answers
step 1 / 10| makeSound() | move() | |
|---|---|---|
| Dog | ? | ? |
| Cat | ? | ? |
| Car | ? | ? |
Three unrelated types. Two messages you want to send to all of them.for (const thing of things) thing.makeSound()
class Dog:
def make_sound(self): return "woof"
class Cat:
def make_sound(self): return "meow"
class Car:
def make_sound(self): return "honk"
for thing in (Dog(), Cat(), Car()):
print(thing.make_sound())
# the loop never checks a typeCheck yourself
The point of polymorphism is…