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 browser
1# Program to demonstrate polymorphism
2
3class Cat:
4 def speak(self):
5 print("Meow")
6
7class Dog:
8 def speak(self):
9 print("Woof")
10
11def animal_speak(animal):
12 animal.speak()
13
14animal_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.