Polymorphism in Python Example-DecodingDevOps

Polymorphism means that using different form to complete one particular task. it means that the same function is defined on the object of different types that is the same function name being used for different types. simply one task can be performed in one or more different ways. it means polymorphism is an ability to use the common interface for multiple forms which are data types. it allows us to automatically do the correct behavior even if what we are working with can take many different forms. let’s check an example:  

class Dog:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return self.name+' says Woof!'
    
class Cat:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return self.name+' says Meow!' 
    
niko = Dog('Niko')
felix = Cat('Felix')

print(niko.speak())
print(felix.speak())

OUTPUT:

Niko says Woof!
Felix says Meow!

Here we have a Dog class and a Cat class, and each has a .speak() method. When called, each object’s method returns a result unique to the object. There a few different ways to demonstrate polymorphism. First, with a for loop:

for pet in [niko,felix]:
    print(pet.speak())

OUTPUT:

Niko says Woof!

Felix says Meow!

Another is with functions:

def pet_speak(pet):
    print(pet.speak())

pet_speak(niko)
pet_speak(felix)

OUTPUT:

Niko says Woof!

Felix says Meow!

Leave a Reply

Your email address will not be published. Required fields are marked *