Polymorphism with Methods

Use polymorphism by defining the same method name in different classes.

PythonBeginner
Python
# Program to demonstrate polymorphism

class Cat:
    def speak(self):
        print("Meow")


class Dog:
    def speak(self):
        print("Woof")


def animal_speak(animal):
    animal.speak()


animal_speak(Cat())
animal_speak(Dog())

Output

Meow
Woof

Different classes implement the same 'speak' interface, and the function 'animal_speak' works with any such object.