Polymorphism with Methods in Python
Use polymorphism by defining the same method name in different classes.
BeginnerObject-Oriented ProgramsExample 7 of 25
polymorphism-with-methods.py
Run in browser1# Program to demonstrate polymorphism23class Cat:4 def speak(self):5 print("Meow")67class Dog:8 def speak(self):9 print("Woof")1011def animal_speak(animal):12 animal.speak()1314animal_speak(Cat())15animal_speak(Dog())
Output
Meow Woof
What's going on
Different classes implement the same 'speak' interface, and the function 'animal_speak' works with any such object.