Back to course

Polymorphism and Duck Typing

Python Programming: The 0 to Hero Bootcamp

Polymorphism

Polymorphism means 'many forms'. In Python, it refers to the ability of different objects to respond to the same method call (e.g., speak()) in different, specific ways, often achieved through inheritance.

Example (Continuing from Inheritance)

We can treat all animals generically, even though they execute their own unique speak method.

python def animal_sound(animal): # The exact output depends on the object type passed in print(animal.speak())

Assuming Dog and Cat classes from before:

fido = Dog('Fido') luna = Cat('Luna')

animals = [fido, luna]

for creature in animals: animal_sound(creature)

Output:

Fido says Woof!

Luna says Meow.

Duck Typing (Python's Polymorphism)

Python uses a concept called Duck Typing: "If it walks like a duck and quacks like a duck, then it must be a duck."

In Python, we don't care about the object's formal type (is it a Dog or a Cat), only that it has the required method (does it have a speak() method?).

python class Robot: def speak(self): return "BEEP BOOP."

robot = Robot()

animal_sound(robot) # Works, because Robot has a .speak() method.

Output: BEEP BOOP.