Polymorphism and duck typing
Polymorphism is an object-oriented programming concept closely related to inheritance. It allows objects that inherit from the same class to be treated in the same way.
Imagine a class Person
from which two classes Teacher
and Student
inherit. Polymorphism allows treating Teacher
and Student
in the same way, since they inherit from the same class.
For example, both classes have a name
, so a function would not care if an object is of one class or the other.
In Python, this is a little different. It is also much more flexible. Python has what is known as duck typing. There is an associated phrase that says: βIf it walks like a duck and it quacks like a duck, then it must be a duck.β
This is a way of saying that Python does not care about the class or type. If it has the necessary methods, then it works. In this example, you can see two different classes. Python tries to call talk
with each animal. Since they all have the talk
method, it works. But they donβt inherit from the same class.
class Dog:
def talk(self):
print("Woof!")
class Duck:
def talk(self):
print("Quack!")
for animal in Dog(), Duck():
animal.talk()
# Woof! # Quack!
It may seem logical, but in many other programming languages, this would error since these are different types that do not share a common interface.
The following also works. Again, Python does not care what object
you pass it. As long as it has the talk
function, it is enough.
def talk(object):
object.talk()
dog = Dog()
duck = Duck()
talk(dog) # Woof!
talk(duck) # Quack!