Python Polymorphism
Polymorphism is the use of one method name across different classes. Each class gives that method name its own job.
One name, many kinds
len() counts a string, a list, and a dict. Each kind is counted in its own way.
print(len("hello"))
print(len([10, 20, 30]))
print(len({"a": 1, "b": 2}))The same method name
Both classes name their method speak(). Each class gives it a different job.
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
print(Dog().speak())
print(Cat().speak())Duck typing in action
The function never names a class. If the thing has speak(), the call works.
class Duck:
def speak(self):
return "Quack!"
class Robot:
def speak(self):
return "Beep!"
def make_sound(thing):
print(thing.speak())
make_sound(Duck())
make_sound(Robot())One loop, many objects
The loop makes the same call each round. Each object answers in its own way.
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
animals = [Dog(), Cat()]
for animal in animals:
print(animal.speak())Example
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
class Bird:
def speak(self):
return "Tweet!"
animals = [Dog(), Cat(), Bird()]
for animal in animals:
print(animal.speak())Key points
- Polymorphism: one method name can do the right job for each class
- Use the same method name in different classes to use them the same way
- len() works on strings, lists, and dicts
- Duck typing: if an object has the method you call, the call works
In this example, Dog, Cat, and Bird each write speak(). Each method returns a different sound. The list holds one object from each class. The loop calls animal.speak() for each object. Python runs the method that belongs to that object. So one loop prints three different sounds.
Note
Python does not check the class first.
It just tries the method when the code runs.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Why does one loop work for Dog, Cat, and Bird objects?