DS160123 - What Is Polymorphism

  1. The word polymorphism means having many forms.
    For Example,

polymophism-copy
As we can see same species with different forms(colours)

  1. In programming, polymorphism means the same function name (but different signatures) being used for different types.

For Example,

print(len('str')) 
print(len([2,3,4,5])

Here, function len() is same but the data types its working on are different.

  1. The key difference is the data types and number of arguments used in function.
def add(x,y,z=100):
     return x+y+z

add(10,20)
add(100,200,300)

Here, the function and data type are same but no. of arguments are different.

Now, For classes,

class Person:
    def __init__(self,age):
        self.age =age
    
    def reveal(self):
        print(f'I am a person with age of {self.age}')

class Machine:
    def reveal(self):
        print('I am a machine')

class Animal:
    def reveal(self):
        print('I am an animal')

a1 = Animal()
p1 = Person(20)
m1 = Machine()

a1.reveal()
p1.reveal()
m1.reveal()
I am an animal
I am a person with age of 20
I am a machine

Even though method reveal is same, it’s functionality can be changed.

Polymorphism with Inheritance

class Animal:
    def sound(self):
        print('sound of an animal')

class Bird(Animal):
    def sound(self):
        print('sound of an bird')

class Human(Animal):
    pass

h1 = Human()
b1 = Bird()
a1 = Animal()

a1.sound()
b1.sound()
h1.sound()
sound of an animal
sound of an bird
sound of an animal

Now, we know that In Inheritance, child classes inherits all the attributes and methods from parent class.
So, here Bird now has two sound() methods, one of itself and one from Animal class.
Here, the its own method takes priority and gives the output.
While for Human has no method of itself, so its parent method is run.
As Animal is a parent class, its method is directly called.

So, In Inheritance, the polymorphism is used to change the behaviour of particular parent method(s) for specific child class without affecting other child classes.

More Info

Note : When it comes to polymorphism, as function name is same, the order becomes important.
For understanding, Try this

def add(a,b,c,d):
    print(a+b+c+d)

def add(a,b,c=20):
    print(a+b+c)

add(10,20,30,40)

Now change the order of functions.

4 Likes

Awesome explanation, keep sharing your attractive thoughts and ideas.

Great explanation @kharshavardhan31 :star_struck: