Sunday, February 9, 2020

Polymorphism in Python

Polymorphism in Python


Polymorphism


The Python is an object-oriented programming language. Polymorphism is a concept supported by object-oriented programming technologies, along with inheritance, abstraction, and encapsulation. “poly” means many, and “morph” means forms. It means if something can occupy multiple roles than it is known as polymorphism.

For example

l1=len('hello world') #LENGTH OF A STRING
l2=len([34,12,17,16,9]) #LENGTH OF A LIST
l3=len({10,12,45,23,12}) #LENGTH OF A SET
print(l1)
print(l2)
print(l3)

We can provide polymorphism in Python with normal methods, with class methods available in two different classes, or inherited class methods(method overriding).

Applying polymorphism


#Demo polymorphism
print('1.==============================')
l1=len('hello worold') #LENGTH OF STRING
l2=len([34,12,17,16,9]) #LENGTH OF LIST
l3=len({10,12,45,23,12})  #LENGTH OF SET
print(l1)
print(l2)
print(l3)

print('2.method overloading=============')
def sum(a,b,c=0):
  return a+b+c
  
print(sum(3,5,12))
print(sum(3,5))

print('3================================')
#method m() belongs to both classes A and B, and works differently in both classes
class A:
  def m(self):
    print("i am a method in class A")

class B:
  def m(self):
    print("i am a method in class B")
    
a1=A()
a2=A()
b1=B()
b2=B()
t=[a1,a2,b1,b2]
for ob in t:
  ob.m()


Output:
1.==============================
12
5
4
2. method overloading=============
20
8
3================================
i am a method in class A
i am a method in class A
i am a method in class B
i am a method in class B

Polymorphism in the inherited classes


Method overriding


Polymorphism can be achieved with inheritance. This type of inheritance is termed as method overriding. A subclass can override a method declared in a superclass. It means a subclass can have its own version or implementation of the inherited method.


method overriding in Python
method overriding


Try yourself: