Login Register

Python Polymorphism Explained In Details

What Is Python Polymorphism?

The word polymorphism originally comes from the Greek language:

  • Poly → means “many”
  • Morphē → means “forms”

Python polymorphism means “one action, many works”. It allows a single function, operator, or method to work with multiple objects.

Imagine a main switch board in your home, you press one button but:

  • A washing machine starts washing.
  • A computer starts booting.
  • A fridge starts cooling.

In Python, polymorphism allows you to write code that can handle different types of objects using the same method name.

Why Is Polymorphism Important?

  • Polymorphism enhances code reusability and flexibility.
  • It allows us to design easy systems that can be modified using a single function or method.
  • This reduces the need for duplicate code.

Types of Polymorphism in Python

1) Method Overriding (Runtime Polymorphism):

When a child class creates a method with the same name as a parent class method, but its behavior (works) is different, it is called method overriding.

It means, a child class can modify its method with different values.

Code example:

class Device:
def status(self):
return "Status information not available."

class SmartLight(Device):
def __init__(self, brightness):
self.brightness = brightness

def status(self):
return f"Light is ON with brightness level: {self.brightness}%"

class SmartFan(Device):
def __init__(self, speed):
self.speed = speed

def status(self):
return f"Fan is running at speed setting: {self.speed}"

# Polymorphism using method overriding
devices = [
SmartLight(70),
SmartFan(3),
Device()
]

for d in devices:
print(d.status())

Output:

Light is ON with brightness level: 70%
Fan is running at speed setting: 3
Status information not available.

2) Operator Overloading:

All the operators like +, *, and> can behave differently depending on the type of values. It means the same operator can perform different tasks like adding values, joining strings, merging lists, etc.

Example of Operator Overloading:

class TimeSlot:
def __init__(self, hours, minutes):
self.hours = hours
self.minutes = minutes

# Overloading the + operator
def __add__(self, other):
total_hours = self.hours + other.hours
total_minutes = self.minutes + other.minutes

# Convert 60 minutes into 1 hour
if total_minutes >= 60:
extra_h = total_minutes // 60
total_hours += extra_h
total_minutes = total_minutes % 60

return TimeSlot(total_hours, total_minutes)

def __str__(self):
return f"{self.hours}h {self.minutes}m"


# Creating TimeSlot objects
t1 = TimeSlot(1, 50)
t2 = TimeSlot(2, 20)

# Adding two objects
result = t1 + t2

print("Total Duration:", result)

Output:

Total Duration: 4h 10m

3) Duck Typing:

Python doesn’t care about objects; it only cares about what the object can do. If an object walks like a duck, speaks like a duck, so Python considers it a duck.

In simple words, a Python function only needs that the object has the required method. For example:

class Fan:
def start(self):
return "Fan has started spinning."

class Laptop:
def start(self):
return "Laptop has booted successfully."

def power_on(device):
# Duck Typing in action → only checks if device has .start()
print(device.start())

# Creating objects
room_fan = Fan()
work_laptop = Laptop()

# Using the same function with different object types
power_on(room_fan)
power_on(work_laptop)

Output of this code:

Fan has started spinning.
Laptop has booted successfully.

4) Method Overloading (Limited):

Python does not support traditional method overloading (using the same method name with different parameters).

Example code: Smart Greeting System

class Greeter:
def greet(self, name=None, mood=None):
# No name given
if name is None:
return "Hello there!"

# Name given, but no mood
if mood is None:
return f"Hello {name}!"

# Name + mood both given
return f"Hello {name}, you seem {mood} today!"

g = Greeter()

print(g.greet()) # No info
print(g.greet("Parth")) # Only name
print(g.greet("Parth", "excited")) # Name + mood

Output will be this:

Hello there!
Hello Parth!
Hello Parth, you seem excited today!

Real-Life Applications of Polymorphism

  1. Framework Design: Polymorphism is widely used in frameworks to create reusable components.
  2. Game Development: We can also use the same behaviors for different types of game characters.
  3. Data Processing: Implement common methods for different data structures.