In this tutorial, we’ll learn about Duck Typing. Duck Typing in python is one way of implementing Polymorphism. This term comes from a saying “If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.
This must sound strange to you but what you need to know from this is the behavioral concept from the statement like If something matches Duck, it is a Duck.
Let’s understand this using an example.
class Fruit:
def type(self):
print("I am a Fruit")
print("I am Tasty")
class Veggie:
def type(self):
print("I am a Veggie")
print("I am Healthy")
class Plant:
def name(self, plantobj):
plantobj.type()
plantobj = Veggie()
plant1 = Plant()
plant1.name(plantobj)
We first created three classes named Fruit
, Veggie
, and Plant
. We first defined a method called name
inside Plant
with one required parameter that is plantobj
and we then called another function type
inside the method.
We have already defined plantobj
as a parameter but haven’t defined it yet which we’ll perform later. This is also called Dynamic Typing.
Now notice that we have defined the same method, type
in both the classes Fruit and Veggie. Now when we call the method name
, it requires a parameter. This parameter is the object of the class that we want to use.
You can use any class object but you need to make sure that the class should have the method type that has been called. Let’s check the output of the above example.
I am a Veggie
I am Healthy
Now, if we change the object to Fruit class object,
plantobj = Fruit()
plant2 = Plant()
plant2.name(plantobj)
Output :
I am a Fruit
I am Tasty
Now, if you read the statement again, “If it behaves like a duck, swims like a duck, and quacks like a duck, then it probably is a duck. In the same way, we have an object plantobj
which has a method called type, we’re good because we’re not concerned about which class object it is.
This is known as Duck Typing.