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.
ON THIS PAGE
Polymorphism python
A rectangle appears in different shapes in different situations. Similarly polymorphism works. Here are three types of polymorphism in python VIZ: Method, Object, and Variable.

Method polymorphism
Here is the method with three arguments. The third argument value initialized with zero (c=0). I have supplied one time two arguments. The other time three arguments. For each, it gives an output. This way 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
Object polymorphism
Here 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
Variable polymorphism
Here a class can take multiple variables(n). There is no fixed limit. And you will get a result different for each input.
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 get 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
You must be logged in to post a comment.