Polymorphism is the core feature of any object oriented programming language. Learn how to implement polymorphism in Python.
Polymorphism in Python
In Python, polymorphism is applied by using the same function for different classes or data types. Polymorphism in Python allows flexibility and easier extension of code. It promotes the design of a code which is re-usable.
What is polymorphism?
In its most basic sense, polymorphism refers to something having many forms. For example, there are different types of vehicles each having similar attributes like body, tyres, engine. However the implementation is different on different vehicles. A sports car and a truck are both vehicles but each have a different implementation of an engine . Similarly, in object-oriented programming, having an object or function doing the same thing but in different ways, defines the purpose of polymorphism.
Using an example with one of Python’s inbuilt functions which works with different data types, let us understand what this boils down to. The max() function is one such example.
# Code snippet for displaying how polymorphism
# works in Python using the max() function.
max_int = max(2020, 2021)
max_str = max('cat', 'dog')
print(f"The largest item between 2020 and 2021 is {max_int}")
print(f"The largest item between 'cat’ and ‘dog’ is '{max_str}'")
It is possible to call the max() function with arguments of different types, in this case using int and str. max_int will give the largest value between the two numbers, 2021. On the other hand, with max_str, the lexicographically largest value between the words cat and dog will be returned, dog. It is important to note that although the same function is being called, the output differs depending on the data type of the argument passed.
How is polymorphism implemented in Python?
To implement polymorphism in Python, there are essentially three ways.
- Polymorphism using class methods
- Polymorphism using a function taking different object types
- Polymorphism using method overriding
The above will be discussed in detail and demonstrated using examples.
Polymorphism using class methods
This can be achieved by using the same method names for different classes. Let’s look at the below two classes. Both have a method get_vehicle_size().
class car():
def get_vehicle_size(self):
return "Medium"
class bus():
def get_vehicle_size(self):
return "Very Large"
As can be seen in the next code snippet, it is possible to iterate through a list having different objects, in this case of type car or bus, and call the vehicle_size() function. This can be done without having to worry about the type of the object because each class has an implementation of that common method.
car1 = car()
bus1 = bus()
vehicle_list = [car1, bus1]
for vehicle in vehicle_list:
vehicle.get_vehicle_size()
Polymorphism using a function taking different object types
For this, one needs to implement a generic function which takes different object types as arguments and produces a result irrespective of the type passed.
Taking car and bus from example above, the table below shows how the calling of method get_vehicle_size() can be done with and without polymorphism.
Without polymorphism
def car_vehicle_size(car):
print(car1.get_vehicle_size())
def bus_vehicle_size(bus):
print(bus.get_vehicle_size())
car1 = car()
car_vehicle_size(car1)
bus1 = bus()
bus_vehicle_size(bus1
def vehicle_size(vehicle):
print(vehicle.get_vehicle_size())
car1 = car()
vehicle_size(car1)
bus1 = bus()
vehicle_size(bus1)
Without polymorphism, we would need to create separate functions since the arguments are different types. This does not promote code re-usability. Applying polymorphism here would look like the right code snippet. One generic function is defined,
vehicle_size(vehicle),
where vehicle can be either car or bus.
Polymorphism using method overriding
When a child class needs to give a different output than that of the parent, a method can be re-implemented in the child class using the same name. This is method overriding. As a result, if an instance of the parent class calls the method, the output will match whatever is implemented in the parent. On the other hand, if the caller is a child instance, the output will then match whatever is implemented in the child class. This gives the possibility to call methods in inherited classes without worrying about how the implementation is different for each sub-class. Let’s check out an example below.
# Code snippet for displaying how polymorphism
# works in Python using method overriding.
class vehicle():
def description(self):
print("This is a vehicle.")
class bus(vehicle):
def description(self):
print("This is a bus vehicle.")
bus1 = bus()
bus1.description()
In the above example, the class bus inherits from the parent class vehicle, but prints out a different value when the description() method is called. Thanks to polymorphism, the output of bus1.description() will be what is implemented in the child class, “This is a bus vehicle.”, as the interpreter recognises that this has been overridden.
Conclusion
This is an overview of what polymorphism is and how it is implemented in Python. There are various advantages of using it, as discussed and displayed in the code snippets, and which ultimately leads to easier, useful and more maintainable code.