Skip to main content
Albero Academy

Polymorphism

Different types responding to the same method call — duck typing in action.

Object-Oriented Programming9 min

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":

same call, different behaviour
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:

one function, any shape
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

  1. 01Polymorphism: the same method call works across different types, each in its own way.
  2. 02Python uses duck typing — having the method is what matters, not the class.
  3. 03Write code against a behaviour so new conforming types work with no changes.
  4. 04Method overriding in subclasses is one form of polymorphism.
  5. 05It is the basis of extensible, loosely-coupled design.

Finished this chapter?

Mark it complete to track your progress through Python.