0
0
Pythonprogramming~5 mins

Purpose of polymorphism in Python

Choose your learning style9 modes available
Introduction

Polymorphism lets us use the same action in different ways for different things. It helps make code simple and flexible.

When you want to use one function name to do different tasks depending on the object.
When you have different types of objects but want to treat them the same way in your code.
When you want to add new types without changing existing code.
When you want to write code that works with many kinds of objects easily.
Syntax
Python
class Animal:
    def sound(self):
        pass

class Dog(Animal):
    def sound(self):
        print("Bark")

class Cat(Animal):
    def sound(self):
        print("Meow")

animals = [Dog(), Cat()]
for animal in animals:
    animal.sound()

Polymorphism often uses methods with the same name in different classes.

It works well with inheritance but can also be used with other techniques.

Examples
Both Bird and Airplane have a fly method. We call fly on each without checking the type.
Python
class Bird:
    def fly(self):
        print("Bird is flying")

class Airplane:
    def fly(self):
        print("Airplane is flying")

for thing in [Bird(), Airplane()]:
    thing.fly()
The add function works for numbers and strings because + means different things for each type.
Python
def add(x, y):
    return x + y

print(add(2, 3))
print(add('Hi, ', 'there!'))
Sample Program

Both Square and Circle have an area method. We call area on each shape without caring about its type.

Python
class Shape:
    def area(self):
        pass

class Square(Shape):
    def __init__(self, side):
        self.side = side
    def area(self):
        return self.side * self.side

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius
    def area(self):
        return 3.14 * self.radius * self.radius

shapes = [Square(4), Circle(3)]
for shape in shapes:
    print(f"Area: {shape.area()}")
OutputSuccess
Important Notes

Polymorphism helps avoid long if-else or switch statements checking types.

It makes code easier to extend and maintain.

Summary

Polymorphism means one action can work in different ways.

It helps write flexible and simple code.

It is often used with classes and methods sharing the same name.