Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is polymorphism in Python

Understanding Polymorphism: The Basics

Imagine you have a universal remote that can control various devices like your TV, air conditioner, and home theater system. You press the 'power' button, and the appropriate device turns on or off. This remote is 'polymorphic' – a single interface controlling multiple objects.

In programming, polymorphism is a concept that refers to the ability of a single function or method to work in different ways depending on the object it is acting upon. It's derived from Greek words 'poly' (many) and 'morph' (form). In essence, polymorphism allows objects of different classes to be treated as objects of a common superclass.

Polymorphism in Python: A Closer Look

Python, being an object-oriented programming language, supports polymorphism. This means that in Python, different classes can have methods with the same name. Depending on the object we use, the correct method is dynamically used at runtime.

Here's a simple example to illustrate this:

class Dog:
    def speak(self):
        return "Woof!"

class Cat:
    def speak(self):
        return "Meow!"

def animal_sound(animal):
    print(animal.speak())

# Create instances of Dog and Cat
dog = Dog()
cat = Cat()

# Call animal_sound with different objects
animal_sound(dog)  # Outputs: Woof!
animal_sound(cat)  # Outputs: Meow!

In the example, both Dog and Cat classes have a method named speak, but they return different sounds. The function animal_sound doesn't need to know what kind of animal it's dealing with; it just calls the speak method on whichever animal object is passed to it.

Types of Polymorphism

Polymorphism manifests in two primary forms: compile-time polymorphism and runtime polymorphism. In Python, we mostly deal with runtime polymorphism, which occurs when the method to be executed is determined at runtime.

Method Overriding

One way to achieve polymorphism in Python is through method overriding, where a subclass provides a specific implementation of a method that is already defined in its superclass.

class Animal:
    def speak(self):
        raise NotImplementedError("Subclasses must implement this method")

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

# Now, let's use the Animal interface
def animal_sound(animal):
    print(animal.speak())

dog = Dog()
cat = Cat()

animal_sound(dog)  # Outputs: Woof!
animal_sound(cat)  # Outputs: Meow!

Here, we have an Animal class with a speak method, and Dog and Cat classes override this method to provide their specific implementations.

Operator Overloading

Polymorphism can also be seen in operator overloading, where an operator can perform differently based on the types of objects it is used with.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    # Overloading the '+' operator
    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

point1 = Point(1, 2)
point2 = Point(2, 3)
point3 = point1 + point2
print(point3.x, point3.y)  # Outputs: 3 5

In this example, the + operator is overloaded to add two Point objects together, creating a new Point with the sum of their coordinates.

Polymorphism in Everyday Coding

When you start building more complex programs, you'll often find yourself using polymorphism without even realizing it. For instance, if you're writing a program that needs to save data, you might have a FileSaver class with a method save. If later on, you decide to save data to the cloud instead of a file, you can create a CloudSaver class with a save method. Your code that calls the save method doesn't need to change, because it's polymorphic.

Polymorphism and Inheritance

Polymorphism is closely related to inheritance, as it allows a subclass to have a different implementation of a method that is already defined in its superclass. This relationship makes code more reusable and easier to maintain.

The Power of Polymorphism

The real power of polymorphism lies in its ability to simplify code and improve its maintainability. It allows you to write more general and reusable code. Instead of writing separate functions for each object, you can write one function that works with all objects that share a common interface.

Conclusion

In the grand tapestry of Python programming, polymorphism is like the threads that allow different patterns to emerge from the same fabric. It's a concept that, once understood, can greatly enhance the elegance and efficiency of your code. Polymorphism enables you to write functions that are agnostic to the specific types of objects they handle, leading to code that's not only more flexible but also more expressive. As you continue your journey in Python and object-oriented programming, embracing polymorphism will surely open doors to creating more dynamic and powerful applications. Remember, like the universal remote, a polymorphic piece of code can bring to life an entire ecosystem of objects with a single touch.