Polymorphism in Python with Examples
One of the important concepts under Object-oriented programming is Polymorphism.
In this article, we’ll see what is polymorphism in python, how python polymorphism works.
We will also learn how we can implement it in our own Python programs.
What is Polymorphism in Python?
Polymorphism gives you the ability to represent objects of different types using a single interface.
A real-life example is You.
You act as a student when you are at college, you act like a son/daughter when you’re at home, you act like a friend when you’re surrounded by your friends.
Now the analogy here is, different personalities of that of a student, a son/daughter, a friend are all analogous to objects of different types.
And a single interface (i.e., you) represents all these different types( i.e. your different personalities).
Understanding Polymorphism in Python
Python can implement polymorphism in many different ways. Python, like many other languages, also provides built-in implementations of Polymorphism.
Let’s look at the examples that illustrate built-in implementations of polymorphism in Python.
Later in this article, we’ll see the various ways in which we can implement Polymorphism in our own programs.
Built-in implementation of Polymorphism
a. Polymorphism in ‘+’ operator
- You might have used the ‘+’ arithmetic python operator multiple times in your programs.
- And chances are, you might have used it with multiple different types.
- This right here is an implementation of polymorphism in Python.
- You use the same + symbol whether you want to add two integers, or concatenate two strings, or extend two lists.
- The + operator acts differently depending on the type of objects it is operating upon.
For integers, it performs arithmetic addition and returns an integer:
>>> x = 1 + 2 >>> print(x)
Output:
>>>
Whereas for strings, it concatenates them and returns a new string:
>>> x = "TechVidvan says " + "Hello" >>> print(x)
Output:
>>>
And for two lists, it returns a new list which contains elements of both the original lists:
>>> x = [1, 2, 3] + [10, ‘TechVidvan’] >>> print(x)
Output:
>>>
b. Polymorphism in built-in method
- Python also implements polymorphism using methods.
- For instance, take the len() method that returns the length of an object.
- The len() method is capable of processing objects of different data types.
- Let’s look at the code example below:
For a list, it returns the number of elements in the list.
>>> l = [1, 2, 3, 4, 5] >>> length = len(l) >>> print(length)
Output:
>>>
For a string, it returns the number of characters within it.
>>> s = “TechVidvan” >>> length = len(s) >>> print(length)
Output:
>>>
For python dictionary, it returns the number of keys.
>>> d = {1: “Archie”, 2: “Brady”, 3: “Charlie”} >>> length = len(d) >>> print(length)
Output:
>>>
We have got a high-level view of what polymorphism is and how Python implements it.
Let’s now dive into how we can implement polymorphism ourselves in our Python program.
Polymorphism in user-defined methods
In the below example, we have two classes ‘Rectangle’ and ‘Square’. Both these classes have a method definition ‘area’, that calculates the area of the corresponding shapes.
class Rectangle: def __init__(self, length, breadth): self.l = length self.b = breadth def area(self): return self.l * self.b class Square: def __init__(self, side): self.s = side def area(self): return self.s ** 2 rec = Rectangle(10, 20) squ = Square(10) print("Area of rectangle is: ", rec.area()) print("Area of square is: ", squ.area())
Output:
Area of square is: 100
>>>
Here, we implemented polymorphism using the method area(). This method works on objects of the types– Rectangle and Square. And it operates differently on objects of different classes.
We can also achieve polymorphism with inheritance.
Let’s see how.
Polymorphism with Inheritance in python
A child class inherits all the attributes and methods of its parent class. But we can provide one or more methods with a different method definition within the child class.
We call this process “method overriding” and such methods “overridden” methods.
Overridden methods have the exact same external interface (method name, number, and type of method parameters) as the parent class’s method but have a different internal implementation. This allows the child class to tailor or extend the functionality of the parent class to meet specific needs.
By using method overriding, we achieve polymorphism, where the same method name can exhibit different behaviors depending on the object that invokes it. This enhances code reusability and makes our programs more flexible and easier to maintain.
Let’s look at a very simple example:
#parent class class Human: def who_am_i(self): print("I am a Human") #child class class Teacher(Human): def who_am_i(self): print("I am a Teacher") t = Teacher() t.who_am_i()
Output:
Here, we implement polymorphism by overriding the method who_am_i() and providing it with a different implementation in the child class Teacher.
Summary
Hope you got a clear understanding of what polymorphism is and how do we implement it in Python. You’ll come across Polymorphism in many languages that support object-oriented programming paradigm.
So make sure to be thorough while understanding it.
In other languages, we can achieve polymorphism with method overloading too, but Python does not support it.