
Polymorphism in Python with Examples
Polymorphism in Python with Examples: Polymorphism is an important concept in Python’s object-oriented programming (OOP) that allows objects to be treated in multiple ways. It enhances code flexibility, readability, and reusability by enabling a single method or operator to behave differently based on the input.
What is Polymorphism in Python?
Polymorphism in Python with Examples: Polymorphism refers to the ability of a function, method, or operator to operate on different data types or objects. Python achieves polymorphism through:
- Method Overloading
- Method Overriding
- Operator Overloading
Polymorphism in Python with Examples
1. Polymorphism in Operators
Operators like +, -, *, etc., can behave differently based on the data types they are used with. This is called operator overloading.
Example of Operator Overloading:
p = 55
q = 77
r = 9.5
g1 = “Software Moji”
g2 = ” Moji!”
print(“Sum of two integers:”, p + q)
print(“Data type of result:”, type(p + q))
print(“Sum of integer and float:”, q + r)
print(“Data type of result:”, type(q + r))
print(“Concatenated string:”, g1 + g2)
print(“Data type of result:”, type(g1 + g2))
Output:
Sum of two integers: 132
Data type of result: <class ‘int’>
Sum of integer and float: 86.5
Data type of result: <class ‘float’>
Concatenated string: Software Moji Moji!
Data type of result: <class ‘str’>
This example shows how Python’s + operator behaves differently when used with integers, floats, and strings, demonstrating polymorphism.
2. Polymorphism in User-defined Methods
Python allows user-defined methods to perform different behaviors based on the class they belong to.
Example of Polymorphism in Methods:
from math import pi
class Square:
def __init__(self, length):
self.l = length
def perimeter(self):
return 4 * self.l
def area(self):
return self.l * self.l
class Circle:
def __init__(self, radius):
self.r = radius
def perimeter(self):
return 2 * pi * self.r
def area(self):
return pi * self.r ** 2
# Initialize objects
sqr = Square(10)
c1 = Circle(4)
print(“Perimeter of Square:”, sqr.perimeter())
print(“Area of Square:”, sqr.area())
print(“Perimeter of Circle:”, c1.perimeter())
print(“Area of Circle:”, c1.area())
Output:
Perimeter of Square: 40
Area of Square: 100
Perimeter of Circle: 25.132741228718345
Area of Circle: 50.26548245743669
Here, both classes define perimeter() and area() methods showcasing polymorphism in user-defined methods.
3. Polymorphism in Built-in Functions
Python’s built-in functions like len() work with various data types, showcasing polymorphism.
Example of Polymorphism with len() Function:
print(“Length of string:”, len(“Software Moji Moji”))
print(“Length of list:”, len([“Python”, “Example”, “Code”]))
print(“Length of dictionary:”, len({“Name”: “Software Moji”, “Type”: “Education”}))
Output:
Length of string: 18
Length of list: 3
Length of dictionary: 2
The len() function demonstrates polymorphism by operating on strings, lists, and dictionaries.
4. Polymorphism and Inheritance
Polymorphism can also be achieved through inheritance by method overriding.
Example of Polymorphism in Inheritance:
class BaseClass:
def __init__(self, name):
self.name = name
def area(self):
pass
class Rectangle(BaseClass):
def __init__(self, length, breadth):
super().__init__(“Rectangle”)
self.length = length
self.breadth = breadth
def area(self):
return self.length * self.breadth
class Triangle(BaseClass):
def __init__(self, height, base):
super().__init__(“Triangle”)
self.height = height
self.base = base
def area(self):
return 0.5 * self.base * self.height
a = Rectangle(90, 80)
b = Triangle(77, 64)
print(“Shape:”, b.name)
print(“Area of Triangle:”, b.area())
print(“Shape:”, a.name)
print(“Area of Rectangle:”, a.area())
Output:
Shape: Triangle
Area of Triangle: 2464.0
Shape: Rectangle
Area of Rectangle: 7200
Both area() methods deliver unique results for different shapes, showcasing polymorphism.
5. Polymorphism with Class Methods
Different classes can have methods with identical names that behave differently based on the class object used.
Example of Polymorphism with Class Methods:
class Amazon:
def __init__(self, name, price):
self.name = name
self.price = price
def info(self):
print(f”Amazon Product: {self.name} costs {self.price} rupees.”)
class Flipkart:
def __init__(self, name, price):
self.name = name
self.price = price
def info(self):
print(f”Flipkart Product: {self.name} costs {self.price} rupees.”)
FLP = Flipkart(“iPhone”, 25000)
AMZ = Amazon(“iPhone”, 40000)
for product in (FLP, AMZ):
product.info()
Polymorphism in Python with Examples Output:
Flipkart Product: iPhone costs 25000 rupees.
Amazon Product: iPhone costs 40000 rupees.
This demonstrates polymorphism by calling the same method info() from two different classes.
Summary:
✅ Polymorphism allows Python objects and methods to behave differently based on input or object type.
✅ Achieved through method overloading, overriding, and operator overloading.
✅ Enhances code reusability and flexibility for efficient programming.
By mastering Python’s polymorphism concepts, you can write cleaner, scalable, and more flexible code for real-world applications.