Polymorphism is a fundamental concept of object-oriented programming (OOP). Polymorphism refers to the ability to have multiple forms. For example, a man in the office behaves like an employee, a father at home, a friend at a party, and a college student. This means the same person is adapting to different roles based on the situation.
What is Polymorphism in Python?
Polymorphism in Python refers to the ability to use a single object multiple times with different aspects. Using polymorphism, you can use the same function in multiple classes for different uses. It’s like having a universal remote control that works with various devices, each responding according to its own functionality. It is mostly used in inheritance where the parent and child class both use the same function but the output is entirely different for both classes.
Types of Polymorphism in Python
- Operator overloading: Operator overloading allows the same operator to have different meanings based on the context, such as using + for both addition and string concatenation.
- Function polymorphism: It refers to the ability of a function to have multiple forms or behaviors depending on the context in which it’s used. Like the len() function which can return the length of strings, lists, and dictionaries.
- Class polymorphism: Class polymorphism allows different classes to have methods with the same name, which enables objects of these classes to be used interchangeably in certain contexts.
- Method overriding: Method overriding occurs when a child class provides a specific implementation of a method that is already defined in its parent class, allowing for customized behaviour.
There are several advantages of using polymorphism in Python. So, let’s take a look at some advantages of using polymorphism in Python.
Advantages of polymorphism in Python
- It is beneficial to reuse existing code for new applications.
- The same function can be used for different data types
- A single function can manage different inputs, which simplifies the overall code.
- Code clarity and organization are improved, which improves readability.
- Multiple methods with the same name can be used, which allows for method overloading.
Now, let’s address each method in a detailed manner with respect to how they are used with Python.
Operator Overloading
Operator overloading allows you to use the same operator to have different behaviours based on the types of operands you are working with. It is a form of ad-hoc polymorphism, where a single operator or function can have multiple implementations depending on the types of the arguments.
As mentioned, it is related to the operator and can be used with any operator, but to make it simple, I’ll be using the example of the + operator:
num1 = 10
num2 = 20
int_sum = num1 + num2
print('Addition of 2 numbers:', int_sum)
str1 = str(num1)
str2 = str(num2)
str_sum = str1 + str2
print('Concatenation of 2 strings:', str_sum)
In the above Python code, I have used the `+` operator two times. First, I used to find the sum of the two numbers and secondly, when I used the same numbers as strings, it gave entirely different output suggesting how the `+` works differently when given different data types.
Here’s the output:
Addition of 2 numbers: 30
Concatenation of 2 strings: 1020
Function Polymorphism
Function polymorphism in Python allows you to use a single function which will act differently based on the kind of arguments passed to it. Function polymorphism is a key feature of object-oriented programming (OOP), which allows for more flexible and reusable code.
Here’s an example where I used one function multiple times with different data types generating different outputs:
def add(x, y):
return x + y
int_result = add(10, 20)
print('Addition of 2 numbers:', int_result)
str_result = add('Hello ', 'World')
print('Concatenation of 2 strings:', str_result)
list_result = add([1, 2, 3], [4, 5, 6])
print('Concatenation of 2 lists:', list_result)
In the above code, I used a function called add, which provides a sum of two variables. I used the add function to add integers, strings and lists, reducing the complexity and length of the code.
Output:
Addition of 2 numbers: 30
Concatenation of 2 strings: Hello World
Concatenation of 2 lists: [1, 2, 3, 4, 5, 6]
Class Polymorphism
Class polymorphism is a core concept in object-oriented programming where objects of different classes are treated as objects of a common base class. This means a single function or method can operate on objects of different types, and the behaviour is determined by the actual object’s class.
Here’s an example of class polymorphism:
class Lion:
def habitat(self):
print('I am a Lion and I live in the savanna.')
def sound(self):
print('Lions roar.')
class Dolphin:
def habitat(self):
print('I am a Dolphin and I live in the ocean.')
def sound(self):
print('Dolphins click and whistle.')
obj1 = Lion()
obj2 = Dolphin()
for animal in (obj1, obj2):
animal.habitat()
animal.sound()
The above code uses class polymorphism using the same method names – habitat and sound in different classes – Lion and Dolphin. Also, I’ve implemented a loop which iterates through these instances and calls habitat and sound methods on each instance.
Output:
I am a Lion and I live in the savanna.
Lions roar.
I am a Dolphin and I live in the ocean.
Dolphins click and whistle.
Method Overriding
Method overriding allows a subclass (or child class) to provide a specific implementation of a method that is already defined in its superclass (or parent class).
This is a key aspect of polymorphism, enabling a subclass to modify or extend the behaviour of a method inherited from a parent class.
Here’s a simple implementation of method overriding:
class Animal:
def sound(self):
print('This animal makes a sound.')
class Dog(Animal):
def sound(self):
print('The dog barks.')
class Cat(Animal):
def sound(self):
print('The cat meows.')
dog = Dog()
cat = Cat()
animals = [dog, cat]
for animal in animals:
animal.sound()
The code defines a superclass Animal with a generic sound method. Two subclasses, Dog and Cat, inherit from Animal and override the sound method to print specific messages: “The dog barks.” and “The cat meows.” respectively.
Instances of Dog and Cat are created and stored in a list. When iterating through this list and calling the sound method on each object, the overridden methods in the subclasses are executed, resulting in the specific sounds being printed.
Output:
The dog barks.
The cat meows.
Conclusion
In this tutorial, I went through what polymorphism is in Python and explained four types of polymorphism in Python using examples. Sure, you can implement polymorphism in other Python scenarios as well; the possibilities are endless.
If you have any queries, drop us a comment.