Explain Polymorphism in Python
What is Polymorphism ?
In programming, polymorphism is a very important concept where a single type entity, such as a method, operator, or object, can represent different types in different situations.
Example Of Built-in Polymorphic Functions
# Python program to explain in-built poly-morphic functions
# len() function used for a string
print(len("hello"))
# len() function used for a list
print(len([100, 200, 300]))
Output
5
3
Examples Of Custom-defined Polymorphic Functions
# A basic Python function to illustrate
# Polymorphism
def addition(a, b, c = 0):
return a + b + c
# Driver code
print(addition(20, 30))
print(addition(20, 30, 40))
Output
50
90
Using Polymorphism with Class Methods
The following code illustrates how Python can similarly utilize two different class types. We iterate through a tuple of objects using a for loop and call the methods without worrying about the specific class type of each object. The assumption here is that these methods exist in each class.
Example
class India():
def capital(self):
print("Capital: New Delhi")
def language(self):
print("Language: Hindi")
def type(self):
print("Type: Developing country")
class USA():
def capital(self):
print("Capital: Washington, D.C.")
def language(self):
print("Language: English")
def type(self):
print("Type: Developed country")
obj_india = India()
obj_usa = USA()
for country_instance in (obj_india, obj_usa):
country_instance.capital()
country_instance.language()
country_instance.type()
Output
Capital: New Delhi
Language: Hindi
Type: Developing country
Capital: Washington, D.C.
Language: English
Type: Developed country
Inheritance with Polymorphism
In Python, Polymorphism allows the definition of methods in the child class with the same name as those in the parent class. With inheritance, the child class inherits methods from the parent class. Nevertheless, there is the flexibility to modify a method in the child class that has been inherited from the parent class. This becomes valuable when the inherited method doesn’t perfectly align with the requirements of the child class. In such scenarios, we can re-implement the method in the child class, a practice referred to as Method Overriding.
Example
class Animal:
def introduction(self):
print("There is a diverse range of animals.")
def movement(self):
print("Many animals can move, but some have distinct modes.")
class cheetah(Animal):
def movement(self):
print("Cheetahs are known for their swift movement.")
class turtle(Animal):
def movement(self):
print("Turtles move at a slow pace.")
obj_animal = Animal()
obj_cheetah = cheetah()
obj_turtle = turtle()
obj_animal.introduction()
obj_animal.movement()
obj_cheetah.introduction()
obj_cheetah.movement()
obj_turtle.introduction()
obj_turtle.movement()
Output
There is a diverse range of animals.
Many animals can move, but some have distinct modes.
There is a diverse range of animals.
Cheetahs are known for their swift movement.
There is a diverse range of animals.
Turtles move at a slow pace.
Function and Object with Polymorphism
It is also feasible to design a function capable of accepting any object, demonstrating polymorphism. In this instance, let’s craft a function named ‘perform_operations()’ designed to take an object, denoted as ‘obj’. Despite the use of the name ‘obj’, any instantiated object can be passed into this function. Subsequently, let’s define a task within the function that involves utilizing the ‘obj’ object. In this scenario, we’ll invoke three methods—namely, ‘get_capital()’, ‘get_language()’, and ‘get_type()’—each defined in the ‘CountryIndia’ and ‘CountryUSA’ classes.
Now, let’s create instances of both the ‘CountryIndia’ and ‘CountryUSA’
classes, assuming they haven’t been instantiated already. With these
instances, we can invoke their actions using the same ‘perform_operations()’ function:
Example
class CountryIndia:
def capital(self):
return "New Delhi is the capital of India."
def language(self):
return "Hindi is the most widely spoken language of India."
def type(self):
return "India is a developing country."
class CountryUSA:
def capital(self):
return "Washington, D.C. is the capital of USA."
def language(self):
return "English is the primary language of USA."
def type(self):
return "USA is a developed country."
def perform_operations(obj):
print(obj.capital())
print(obj.language())
print(obj.type())
obj_india = CountryIndia()
obj_usa = CountryUSA()
perform_operations(obj_india)
perform_operations(obj_usa)
Output
New Delhi is the capital of India.
Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.
Python Polymorphism with Inheritance and Method Overriding
class Creature:
def vocalize(self):
raise NotImplementedError("Subclass must implement this method")
class Dog(Creature):
def vocalize(self):
return "Woof!"
class Cat(Creature):
def vocalize(self):
return "Meow!"
# Create a list of Creature objects
creatures = [Dog(), Cat()]
# Invoke the vocalize method on each object
for creature in creatures:
print(creature.vocalize())
Output
Woof!
Meow!
Conclusion
polymorphism in Python enables the flexibility to use a single entity, such as a function or method, to handle different types. Whether through built-in functions, custom-defined functions, class methods, or inheritance with method overriding, polymorphism enhances code reusability and adaptability. It allows for the seamless interchangeability of objects and methods, promoting a more dynamic and versatile programming approach.