Introduction to Polymorphism in Python

Introduction to Polymorphism

Welcome back! We're continuing our journey into object-oriented programming (OOP) with a new and exciting topic: Polymorphism. You've already learned about classes, objects, and inheritance, which are essential building blocks of OOP. Now, it's time to explore how polymorphism can make your code more flexible and reusable.

Understanding Polymorphism

Polymorphism in Python allows you to call derived class methods through a base class reference. This can make your code more dynamic and general. Essentially, polymorphism enables methods to do different things based on the object it is acting upon, even if they share the same name.

When a method in a derived class has the same name as a method in its base class, the derived class method overrides the method in the base class. This ensures that the call to the method runs the derived class's version of the method, allowing the same method call to perform different tasks depending on the object it is acting upon.

Method Overriding

As we briefly touched on in the previous lesson, method overriding occurs when a derived class provides a specific implementation of a method that is already defined in its base class. The method in the derived class overrides the corresponding method in the base class.

This allows the derived class to offer a specific behavior while still maintaining the same method signature. Imagine different animals like birds, fish, and dogs. Each animal can eat(), move(), and speak(). Even though these actions have the same name for each animal, the implementation for eating, moving, and speaking can vary:

  • Bird: Moving might involve flying.
  • Fish: Moving might involve swimming.
  • Dog: Moving might involve running.

Despite these differences, a single interface (move() method) allows us to handle all animal types polymorphically.

Here’s an example:

Python
class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def speak(self):
        print("Dog barks")

if __name__ == "__main__":
    generic_animal = Animal()
    generic_animal.speak()  # Output: Animal speaks

    dog = Dog()
    dog.speak()  # Output: Dog barks

In this snippet, the Dog class overrides the speak method of the Animal class. When the speak method is called on an instance of Dog, the overridden method in Dog is executed instead of the method in Animal. In contrast to the previous lesson's example, we do not call super().speak() here because we intend to completely override the method from the parent class.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal