Learn Python Programming

Python – Polymorphism


Polymorphism is a word that originated from two Greek words: poly means many and morphos means forms.

If a variable, object or method perform different behavior according to situation, it is called polymorphism.

Polymorphism basically says that the same thing or same object can behave differently in different scenarios.

Polymorphism is an important feature of class definition in Python that is utilized when you have commonly named methods across classes or subclasses.

Let take a scenario to understand better:

If you are a student, you may pay bill by taking it from your parent. But if you are a millionaire and you are paying your bills through the credit card or you might pay through debit card, you might pay by cheque or you might pay through cash, in different ways.

So, since that paying bill is something that is common to a person but the mode or way of paying bill might be changed based on who is paying the bill.

Let look at the below example.

class Animal:
    def talk(self):
        pass

class Cat(Animal):
    def talk(self):
        print("Meow")

class Dog(Animal):
    def talk(self):
        print("Woof")

c = Cat()
c.talk()

d = Dog()
d.talk()

#OUTPUT
Meow
Woof

In the above example, what has been done, We have used the concept of method overriding. But animal.talk() method is present in all animals. However, the cat essentially is also an instance of the animal object. This is Polymorphism is because both cat and dog are animals, but when call talk on it, both of them behave differently. So, same kind of attribute are being called but the behavior is different and that is Polymorphism, where you have multiple forms of the same object.