Polymorphism In Python

What is Polymorphism ?

Polymorphism is a fundamental concept in object-oriented programming (OOP), including Python. It refers to the ability of different types of objects to be treated as if they are instances of a common superclass. This allows objects to be used interchangeably based on their common interface, even though they may have different implementations.

In Python, polymorphism can be achieved through method overriding and method overloading. Here’s a brief explanation of each:

  • Method Overriding
  • Method Overloading

Method Overriding

This occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. When you call the method on an instance of the subclass, the subclass’s implementation is executed instead of the superclass’s implementation.

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


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


class Cat(Animal):
    def speak(self):
        print("Meoww!!!")


dog = Dog()
cat = Cat()
dog.speak()
cat.speak()

# Output
Woof Woof!!!
Meoww!!!

Method Overloading

Unlike some other programming languages, Python does not support traditional method overloading where multiple methods with the same name but different parameters can exist. However, you can achieve a form of method overloading using default parameter values or variable arguments (*args and **kwargs).

Example using default parameter values

class MathUtil:
    # This add() is Polymorphic.
    def add(self, a, b=0):
        return a + b


util = MathUtil()
print(util.add(100, 100))
print(util.add(100))

# Output
200
100

Example using variable arguments

class MathOperations:
    def add(self, *args):
        return sum(args)


util = MathOperations()
print(util.add(1, 2, 3, 4, 5))
print(util.add(1, 2))
print(util.add(1, 2, 3, 4))

# Output
15
3
10

In both cases, the add method is polymorphic because it can accept different numbers of arguments.

These are just basic examples to illustrate polymorphism in Python. Polymorphism is a powerful concept that allows you to write flexible and reusable code by treating objects of different types uniformly.

Leave a Reply