Implementing Polymorphism Through Method Overriding
In this lesson, you will learn how to write functions that treat different objects interchangeably by relying on their shared method names.
The Power of Shared Interfaces
Polymorphism literally means "many forms." In programming, this means we can write a single function that works on different types of objects, provided those objects all share a method with the same name. Because we have already learned how to override parent methods in subclasses, we can ensure that every object behaves in its own unique way when we call that shared method.
Imagine we have a base class Animal and two subclasses, Dog and Cat. Both override a speak() method.
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
Triggering Behavior Polymorphically
The magic happens when we write a function that doesn't care what the object is, only that it has a speak() method. We call this "duck typing"—if it walks like a duck and quacks like a duck, we treat it like a duck.
def make_it_speak(animal):
# We don't check if it's a Dog or Cat.
# We just know it has a speak() method.
print(animal.speak())
my_dog = Dog()
my_cat = Cat()
make_it_speak(my_dog) # Output: Woof!
make_it_speak(my_cat) # Output: Meow!
By defining a standard interface (the speak method) across different classes, we decouple our code. The make_it_speak function is now flexible; if you decide to add a Bird class later that also implements speak(), you won't need to change a single line of code inside make_it_speak. The function remains perfectly capable of handling the new type because it relies on the polymorphic interface rather than a specific class type.
Key Takeaway: Polymorphism allows you to write clean, reusable functions that execute unique object logic simply by calling the same method name across different class types.