Understanding Polymorphism in Python

Discover how polymorphism allows methods to take different forms in Python. Polymorphism enables a single method to behave differently in different contexts, especially when overridden in child classes. Learn how Python’s dynamic typing makes polymorphism straightforward.



Python - Polymorphism

What is Polymorphism in Python?

Polymorphism refers to a function or method taking different forms in different contexts. Since Python is dynamically typed, polymorphism is easy to implement.

If a method in a parent class is overridden with different logic in its child classes, the base class method is polymorphic.

Ways of Implementing Polymorphism in Python

Duck Typing in Python

Duck typing means the type of an object is less important than the methods it defines. You can call any method on an object as long as the method exists.

"If it walks like a duck and quacks like a duck, it's probably a duck."

Example

class Duck:
    def sound(self):
        return "Quack, quack!"

class AnotherBird:
    def sound(self):
        return "I'm similar to a duck!"

def makeSound(duck):
    print(duck.sound())

duck = Duck()
anotherBird = AnotherBird()
makeSound(duck)
makeSound(anotherBird)
        
Output

Quack, quack!
I'm similar to a duck!
        

Method Overriding in Python

Method overriding occurs when a method in a subclass has the same name as a method in its superclass but implements different functionality.

Example

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def draw(self):
        return

class Circle(Shape):
    def draw(self):
        print("Draw a circle")

class Rectangle(Shape):
    def draw(self):
        print("Draw a rectangle")

shapes = [Circle(), Rectangle()]
for shape in shapes:
    shape.draw()
        
Output

Draw a circle
Draw a rectangle
        

Overloading Operators in Python

Operator overloading allows custom classes to define how operators behave. For example, adding two vectors using the '+' operator.

Example

class Vector:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __str__(self):
        return f'Vector ({self.a}, {self.b})'

    def __add__(self, other):
        return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(3, 7)
v2 = Vector(6, -3)
print(v1 + v2)
        
Output

Vector (9, 4)
        

Method Overloading in Python

Method overloading occurs when a class has multiple methods with the same name but different parameters. Python does not support this by default, but it can be achieved using variable-length argument lists.

Example

def add(*nums):
    return sum(nums)

result1 = add(5, 15)
result2 = add(5, 15, 25)
print(result1)
print(result2)
        
Output

20
45