3 Python Polymorphism Real time Examples Helpful for Interviews

Poly means many, and morphism means forms. So polymorphism means many forms. Python supports object-oriented concepts like java. Below, you will find examples that explain the polymorphism of method/object/variable. 

Python polymorphism real-time examples

The rectangle behaves in three different ways in different situations. You can find an example here. We will now see these three polymorphisms – Methods, Object, and Variable.

Polymorphism in Python real time examples
Python polymorphism

1. Method polymorphism

Here, I have created a method. And I would supply two and three values in the input. For each, it gives an output. So it is called method polymorphism.

def meth1(a, b, c=0):
    return a + b + c

#Method polymorphism
print(meth1(1, 2))
print(meth1(1, 2, 3))
   

Method polymorphism

Output

3
6

** Process exited - Return Code: 0 **
Press Enter to exit terminal

2. Object polymorphism

Below, you will find an example of object polymorphism. Precisely, the same object gives two different results. Let us see how it works.

Here, the class puppy assigns to two different objects with different inputs. The result is different – not the same. So it tells how object polymorphism works.

class puppy:
    
    def obj1(self, value):
        print(" My Value is : ", value)

#Object polymorphism
c1=puppy()
c2=puppy()

c1.obj1(400)
c2.obj1(300)

Output

 My Value is :  400
 My Value is :  300

** Process exited - Return Code: 0 **
Press Enter to exit terminal

3. Variable polymorphism

In this case, a class can take variables of n. There is no fixed limit. And you will get a result different for each input. Below, you will find an example.

class Demo:
    def mymul(self,*vars):
        mytotal=1
        for loop in vars:
            mytotal *= loop
            print("The Product of arguments is :",mytotal)

myobj=Demo()

myobj.mymul(10,20,30)
myobj.mymul(10,20)
myobj.mymul(10)
myobj.mymul()
myobj.mymul(10,20,30,40)

Output

For each input, you will find an output. The concept of this kind of polymorphism is called python variable polymorphism.

The Product of arguments is : 10
The Product of arguments is : 200
The Product of arguments is : 6000
The Product of arguments is : 10
The Product of arguments is : 200
The Product of arguments is : 10
The Product of arguments is : 10
The Product of arguments is : 200
The Product of arguments is : 6000
The Product of arguments is : 240000

** Process exited - Return Code: 0 **
Press Enter to exit terminal

Related

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.