Python Polymorphism

In this tutorial, you will learn about Polymorphism In Python

Introduction


Polymorphism is one of the four fundamental principles of object-oriented programming (OOP), along with encapsulation, inheritance, and abstraction.

In Python, polymorphism allows objects to be treated as instances of their parent class, enabling code to be written that can work with objects of various types.

There are two main types of polymorphism in Python: compile-time polymorphism (also known as method overloading) and runtime polymorphism (also known as method overriding).

This tutorial will explore both types of polymorphism, providing examples and explanations along the way.

 

Compile-Time Polymorphism (Method Overloading)


Compile-time polymorphism, or method overloading, occurs when multiple methods in the same class have the same name but different parameter lists.

The method that gets called is determined at compile time based on the number and types of arguments passed.

Python does not support traditional method overloading like some other languages, but it provides a way to achieve similar functionality using default arguments and variable-length argument lists.

Example:

class MathOperations:
    def add(self, a, b=None, c=None):
        if b is not None and c is not None:
            return a + b + c
        elif b is not None:
            return a + b
        else:
            return a

# Usage
math_ops = MathOperations()
result1 = math_ops.add(2)
result2 = math_ops.add(2, 3)
result3 = math_ops.add(2, 3, 4)

print(result1)  # Output: 2
print(result2)  # Output: 5
print(result3)  # Output: 9


In this example, the add method is overloaded with different numbers of parameters, allowing the user to call it with one, two, or three arguments.

 

2. Runtime Polymorphism (Method Overriding)


Runtime polymorphism, or method overriding, occurs when a method in a child class has the same name and signature as a method in its parent class.

The child class provides a specific implementation for the method, and the method from the child class is called at runtime.

Example:

class Animal:
    def make_sound(self):
        pass

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

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

# Usage
dog = Dog()
cat = Cat()

print(dog.make_sound())  # Output: Woof!
print(cat.make_sound())  # Output: Meow!


In this example, the make_sound method is overridden in both the Dog and Cat classes, providing specific implementations for each subclass.

 

3. Duck Typing and Polymorphism


Python follows the principle of "duck typing," which means that the type or class of an object is less important than the methods it defines.

If an object quacks like a duck (has the required methods), then it is treated as a duck.

This concept is closely related to polymorphism, as it allows different objects to be used interchangeably based on their behavior rather than their type.

Example:

class Car:
    def drive(self):
        return "Vroom!"

class Bicycle:
    def drive(self):
        return "Pedal, pedal!"

# Function accepting any object with a 'drive' method
def get_vehicle_sound(vehicle):
    return vehicle.drive()

# Usage
car = Car()
bicycle = Bicycle()

print(get_vehicle_sound(car))       # Output: Vroom!
print(get_vehicle_sound(bicycle))   # Output: Pedal, pedal!


In this example, both the Car and Bicycle classes have a drive method, so they can be used interchangeably in the get_vehicle_sound function.

 

Conclusion


Polymorphism is a powerful concept in object-oriented programming that allows for flexibility and extensibility in code.

Whether through compile-time polymorphism (method overloading) or runtime polymorphism (method overriding), Python provides mechanisms for implementing polymorphic behavior.

Understanding and leveraging polymorphism can lead to more modular, reusable, and maintainable code.
 

© 2022-2023 All rights reserved.