8.5 Polymorphism

8.5 Polymorphism

Understanding polymorphism, the ability of different objects to respond to the same method call in different ways.

Polymorphism, which literally means "many forms," is the principle that allows objects of different classes to respond to the same method call, each in its own unique way. This allows for writing more general and flexible code that can work with different types of objects without needing to know the specific details of their class. It just needs to know that they support the common method.
class Cat:
    def make_sound(self):
        return "Meow"

class Dog:
    def make_sound(self):
        return "Woof"

def make_animal_speak(animal):
    # This function doesn't care if the animal is a Cat or a Dog.
    # It just calls the make_sound() method.
    print(animal.make_sound())

cat = Cat()
dog = Dog()

make_animal_speak(cat)
make_animal_speak(dog)

Explore More with AI

Use AI to generate new examples, delve deeper into theory, or get your questions answered.