Polymorphism — "many forms" — lets different types respond to the same method call in their own way. You write code against abehaviour, and any object providing that behaviour just works, whatever its class.
Duck typing
Python doesn't check types — it checks whether the method exists. "If it walks like a duck and quacks like a duck, it's a duck":
class Dog:def speak(self): return "Woof"class Cat:def speak(self): return "Meow"class Duck:def speak(self): return "Quack"for animal in [Dog(), Cat(), Duck()]:print(animal.speak()) # Woof / Meow / Quack — same call, different result
Writing to a behaviour
The payoff: code that works with any conforming type, including ones written later — the essence of extensible design:
def total_area(shapes):return sum(shape.area() for shape in shapes)# Works for ANY object with an .area() method — Circle, Square, Triangle…# Add a new shape class later and this function needs no changes.
Key takeaways
- 01Polymorphism: the same method call works across different types, each in its own way.
- 02Python uses duck typing — having the method is what matters, not the class.
- 03Write code against a behaviour so new conforming types work with no changes.
- 04Method overriding in subclasses is one form of polymorphism.
- 05It is the basis of extensible, loosely-coupled design.
