Home » Python Tutorial » Polymorphism in Python with Example

Polymorphism in Python with Example

Polymorphism is a Greek word. If we break the word into poly and morphism, then it means many forms. Polymorphism in Python is the ability to take many forms.

Suppose you need to find areas of different shapes. In this, shares are different, but the final answer is area. You can then declare an area method in the parent class and define it in the child class. This situation is called polymorphism.

Types of polymorphism

In object-oriented programming, polymorphism has two types.

  1. Method overloading.
  2. Method overriding.

But Python does not support method overloading as the interpreter does not identify the method’s signature feature.

Method overriding is allowed in Python. You can declare a method in the parent class and define it in the child class.

How does polymorphism work in Python?

Python interpreter allows the programmers to declare come methods in the parent class and also define it there. You can override those methods in child class if you want to change the code of any specific method. Due to polymorphism, the Python interpreter recognizes that the method in the child class is overridden so that the interpreter uses the overridden method at the time of execution.

Why do we use polymorphism in Python?

Consider a stack (which is a last-in, first-out list). You might have a program that requires three types of stacks. One stack is used for integer values, one for floating-point values, and one for characters. The algorithm that implements each stack is the same, even though the data being stored differs. In a non-object-oriented language, you would be required to create three different sets of stack routines, with each set using different names. However, because of polymorphism, you can declare the algorithm in the parent class. Then you can inherit it into child class and make changes.

To avoid lengthy coding, we use polymorphism in Python.

How to implement polymorphism in Python?

There are various ways to use Python polymorphism. Many predefined functions and operators use polymorphism concepts like len() and ‘+’ operator.  

Also, we can use polymorphism with user-defined functions, classes, objects, and inheritance. Let’s learn polymorphism in Python with examples.

1. len() function in Python.

Example

mytuple = {1, "one", 'a', 1.343}
print(len(mytuple))

print(len('pradtutorials'))

list = [1,2,3,4,5,6,7,8,9]
print(len(list))

Output

4
13
9

2. ‘+’ operator in Python

Example

a = 10
b = 40
print(a+b)

str1 = "prad"
str2 = "Tutorials"
print(str1+str2)

Output

50
pradTutorials

In the above polymorphism in Python example, we have used arithmetic operators. But in Python, ‘+’ operator has two meanings. When it is used with numerical values, it will add them. On the other hand, if it is used with two strings. The ‘+’ operator will concatenate them. Which means ‘+’ has provided a polymorphism feature.

Polymorphism with functions, class methods, objects, and inheritance.

1. Polymorphic functions.

In the below example, we have declared one function, but we have declared two parameters as default parameters in the time of parameter listing to use one function in three ways.

Example

def area(a,b=0,c=0):
   if b==0 and c==0:
       print("area of square is: ",a*a)
   elif c==0:
       print("area of rectangle is: ",a*b)
   else:
       print("area of rectangular prism is: ",(2*(b*a+c*a+c*b)))

area(4)
area(6,7)
area(3,4,6)

Output

area of square is:  16
area of rectangle is:  42
area of rectangular prism is:  108

2. Polymorphism with class methods.

The below example is of class method polymorphism. We can declare a same-named function in many classes. Python interpreter recognizes each function by its object.

Example

class localcar:
   def brand(self):
       print("Maruti Suzuki")
   def seats(self):
       print("4 or 6 seats")
   def mileage(self):
       print("Average 20-15kmpl")

class supercar():
   def brand(self):
       print("Lamborghini")
   def seats(self):
       print("2 or 4 seats")
   def mileage(self):
       print("Average 4-6 kmpl")

super = supercar()
local = localcar()

for vehicle in(super, local):
   vehicle.brand()
   vehicle.seats()
   vehicle.mileage()

Output

Lamborghini
2 or 4 seats
Average 4-6 kmpl
Maruti Suzuki
4 or 6 seats
Average 20-15kmpl

3. Polymorphism with inheritance.

Polymorphism allows us to define the same named methods in the parent class as well as in the child class. Suppose you have declared one function in the parent class. But you want to make some changes in the child class. Python interpreter allows you to do so. An example is given below.

Example

class shape:
   l = 0
   b = 0
   def area(self,a,b):
      self.l = a
      self.b = b
      print("In parent class")

class rectangle(shape):
   def area(self,a,b):
       print("In child class")
       print("Area of rectangle is :",a * b)

class triangle(shape):
   def area(self,a,b):
       print("In child class")
       print("Area of rectangle is :", (1/2*(a * b)))

shapeobj = shape()
recobj = rectangle()
triobj =triangle()

shapeobj.area(1,2)
recobj.area(5,6)
triobj.area(4,7)

Output

In parent class
In child class
Area of rectangle is : 30
In child class
Area of rectangle is : 14.0
Did you know?
1. Python Strip
2. Python Queue
3. Fibonacci Series In Python
4. Reverse a String in Python
5. Bubble Sort in Python
6. Slicing in Python
7. Recursion in Python
8. Matrix In Python
9. Binary Search in Python
10. Polymorphism in Python

Pin It on Pinterest