Polymorphism in Python
What is Polymorphism?
The concept of Polymorphism is taken from the Greek words Poly (many) and morphism (forms). It means the same function name being uses for different types. This helps programming easier and more intuitive.
There are different ways to implement polymorphism in Python. So, let’s go through and see how polymorphism works in Python.
Example of user defined polymorphic functions:
# A simple Python function to demonstrate # Polymorphism def add(x, y, z = 0): return x + y+z # Driver code print(add(3, 5)) print(add(3, 5, 2))
Polymorphism with class methods:
Below code shows how python uses two different class types in the similar way. Here we created a for loop that iterates through a tuple of objects. Next we need to call the methods without being concerned about which class type each object is. We take up that these methods truly exist in each class.
class India(): def capital(self): print("The capital of India is New Delhi.") def language(self): print("Hindi is the most popular language.") def type(self): print("India is a developing country.") class USA(): def capital(self): print("The capital of USA is Washington, D.C.") def language(self): print("The primary language of USA is English.") def type(self): print("USA is a developed country.") obj_ind = India() obj_usa = USA() for country in (obj_ind, obj_usa): country.capital() country.language() country.type()
Polymorphism with Inheritance:
In inheritance child class inherits the methods from the parent class. However, in some situations, it is possible to modify the method in a child class inherited from the parent class due to the method do not fit into the child class. In such cases, we re-implement method in the child class.This process of re-implementing a method in the child class is referred to as Method Overriding.
class Bird: def intro(self): print("Birds are of many types.") def flight(self): print("Only some birds can fly.") class eagle(Bird): def flight(self): print("Eagle can fly.") class ostrich(Bird): def flight(self): print("Ostriches cannot fly.") obj_bird = Bird() obj_egl = eagle() obj_ost = ostrich() obj_bird.intro() obj_bird.flight() obj_egl.intro() obj_egl.flight() obj_ost.intro() obj_ost.flight()