Polymorphism

Learn Python polymorphism with examples. Understand how methods with the same name can behave differently across classes in object-oriented programming.

Loading...
Polymorphism

Polymorphism allows methods to behave differently based on the object calling them, even if they have the same name.

Example:

class Cat:
    def speak(self):
        print("Cat meows")
 
class Dog:
    def speak(self):
        print("Dog barks")
 
def animal_sound(animal):
    animal.speak()
 
dog = Dog()
cat = Cat()
 
animal_sound(dog)  # Output: Dog barks
animal_sound(cat)  # Output: Cat meows

Here, both Dog and Cat classes define a speak() method, but the behavior depends on the object passed.


👉 Next tutorial: Python Encapsulation

Support my work!