English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, we will learn about polymorphism, different types of polymorphism, and how to demonstrate them in Python with examples.
The literal meaning of polymorphism is the condition that appears in different forms.
Polymorphism is a very important concept in programming. It refers to using a single type entity (method, operator, or object) to represent different types in different scenarios.
Let's take an example:
We know + operator is widely used in Python programs. However, it does not have a single usage.
For integer data types, use + operator to perform arithmetic addition.
num1 = 1 num2 = 2 print(num1+num2)
Therefore, the above program outputs 3
Similarly, for string data types, use + operator to concatenate.
str1 = "Python" str2 = "Programming" print(str1+"\t"+str2)
As a result, the above program outputs : Python Programming
Here, we can see the use of the operator + Different operations are performed on different data types. This is one of the simplest polymorphism phenomena in Python.
There are some functions in Python that are compatible with multiple data types.
One such function is the len() function. It can run with many data types in Python. Let's look at some example cases of this function.
print(len("w3codebox" print(len(["Python", "Java", "C"])) print(len({"Name": "John", "Address": "Nepal"}))
Output result
5 3 2
Here, we can see that many data types (such as strings, lists, tuples, sets, and dictionaries) can use the len() function. However, we can see that it returns specific information about the specific data type.
Polymorphism is a very important concept in object-oriented programming.
For more information on OOP in Python, please visit:Python Object-Oriented Programming
When creating class methods, we can use the concept of polymorphism because Python allows different classes to have methods with the same name.
Then, we can generalize the calls to these methods later by ignoring the object being used. Let's look at an example:
class Cat: def __init__(self, name, age): self.name = name self.age = age def info(self): print(f"I am a cat. My name is {self.name}. I am {self.age} years old.") def make_sound(self): print("Meow") class Dog: def __init__(self, name, age): self.name = name self.age = age def info(self): print(f"I am a dog. My name is {self.name}. I am {self.age} years old.") def make_sound(self): print("Bark") cat1 = Cat("Kitty", 2.5) dog1 = Dog("Fluffy", 4) for animal in (cat1, dog1) animal.make_sound() animal.info() animal.make_sound()
Output result
Meow I am a cat. My name is Kitty. I am 2.5 years old. Meow Bark I am a dog. My name is Fluffy. I am 4 years old. Bark
Here, we have created two classes, Cat and Dog. They have a similar structure and have the same method names info() and make_sound().
However, please note that we have not created a public superclass or linked these classes together in any way. Even so, we can pack these two different objects into a tuple and iterate over them using a common animal variable. This is allowed due to polymorphism.
Like other programming languages, Python's subclasses inherit methods and properties from the superclass. We can redefine certain methods and properties specifically for the subclass, which is calledMethod Overriding(Method Overriding).
Polymorphism allows us to access these overridden methods and properties with the same name as the superclass.
Let's look at an example:
from math import pi class Shape: def __init__(self, name): self.name = name def area(self): pass def fact(self): return "I am a two-dimensional shape." def __str__(self): return self.name class Square(Shape): def __init__(self, length): super().__init__("Square") self.length = length def area(self): return self.length**2 def fact(self): return "Each corner of the square is"90 degrees." class Circle(Shape): def __init__(self, radius): super().__init__("Circle") self.radius = radius def area(self): return pi*self.radius**2 a = Square(4) b = Circle(7) print(b) print(b.fact()) print(a.fact()) print(b.area())
Output result
Circle I am a two-dimensional shape. Each corner of the square is90 degrees. 153.93804002589985
Here, we can see that methods such as __str__ that have not been overridden in the subclass are used in the superclass.
Due to polymorphism, the Python interpreter automatically identifies that the fact() method of object a (Square class) has been overridden. It uses the one defined in the subclass.
On the other hand, since the fact() method of object b has not been overridden, it can be used from the Parent Shape class.
Note:Method overloadingIt is a method that cannot be created with the same name but different parameters in Python.