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
1# 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.
After this program
If the idea is still fuzzy, read Day 11: Classes and Objects in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 object-oriented programs, or see every topic on Python exercises.