🎭 What is Polymorphism in Python?
The word polymorphism means "having many forms". In object-oriented programming, it refers to the ability of different classes to respond to the same method call or function interface in their own unique way. Python achieves polymorphism through Method Overriding, Duck Typing, and Operator Overloading, allowing developers to write flexible and reusable code.
1. Basic Built-in Polymorphism (len() function)
Python's built-in
len() function demonstrates polymorphism by working seamlessly across strings, lists, tuples, and dictionaries.
Python
# len() works across different data types polymorphically
print("String length:", len("Nikita Infotech"))
print("List length:", len(["HTML", "CSS", "Python"]))
print("Dictionary item count:", len({"a": 1, "b": 2, "c": 3}))
Output:
String length: 15
List length: 3
Dictionary item count: 3
Real-Time Example 1: Payment Gateway Integration (Method Overriding)
Different payment processors implement the same
pay() interface method differently.
Python
class StripePayment:
def pay(self, amount):
return f"Processed ₹{amount} securely via Stripe Gateway."
class PayPalPayment:
def pay(self, amount):
return f"Processed ₹{amount} securely via PayPal Account."
class CryptoPayment:
def pay(self, amount):
return f"Processed ₹{amount} securely via Cryptocurrency Wallet."
# Polymorphic function handling any payment processor object
def execute_checkout(gateway, amount):
print(gateway.pay(amount))
execute_checkout(StripePayment(), 2500)
execute_checkout(PayPalPayment(), 4500)
execute_checkout(CryptoPayment(), 12000)
Output:
Processed ₹2500 securely via Stripe Gateway.
Processed ₹4500 securely via PayPal Account.
Processed ₹12000 securely via Cryptocurrency Wallet.
Real-Time Example 2: Duck Typing ("If it walks like a duck...")
Python doesn't check explicit class types; as long as an object has the required method, it can be used.
Python
class PDFExporter:
def export(self, data):
return f"Exporting report data to PDF format: {data}"
class ExcelExporter:
def export(self, data):
return f"Exporting report data to Excel spreadsheet: {data}"
def generate_report(exporter, report_data):
# Duck typing: doesn't care about class name, just checks if .export() exists
print(exporter.export(report_data))
generate_report(PDFExporter(), "Q1 Sales Summary")
generate_report(ExcelExporter(), "Q1 Sales Summary")
Output:
Exporting report data to PDF format: Q1 Sales Summary
Exporting report data to Excel spreadsheet: Q1 Sales Summary
Real-Time Example 3: Polymorphism with Inheritance and Abstract Classes
Enforce polymorphic behavior across geometric shape classes using abstract base classes.
Python
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def calculate_area(self):
pass
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def calculate_area(self):
return self.length * self.width
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def calculate_area(self):
return round(3.14159 * (self.radius ** 2), 2)
shapes = [Rectangle(10, 5), Circle(7)]
for shape in shapes:
print(f"Calculated Area: {shape.calculate_area()}")
Output:
Calculated Area: 50
Calculated Area: 153.94
Real-Time Example 4: Operator Overloading (Magic Methods like __add__)
Customize built-in operators (+, -, *) to work with custom object instances polymorphically.
Python
class ShoppingCart:
def __init__(self, total_amount):
self.total_amount = total_amount
# Overloading the '+' operator using __add__
def __add__(self, other):
return ShoppingCart(self.total_amount + other.total_amount)
def __str__(self):
return f"Cart Total: ₹{self.total_amount}"
cart1 = ShoppingCart(1500)
cart2 = ShoppingCart(3200)
combined_cart = cart1 + cart2 # Calls __add__ automatically
print(combined_cart)
Output:
Cart Total: ₹4700
Real-Time Example 5: Notification Dispatcher
Broadcast alerts across Email, SMS, and Push notification classes using a shared
send() interface.
Python
class EmailAlert:
def send(self, msg): return f"Email sent: {msg}"
class SMSAlert:
def send(self, msg): return f"SMS sent: {msg}"
class PushAlert:
def send(self, msg): return f"Push notification sent: {msg}"
def broadcast_alert(channels, message):
for channel in channels:
print(channel.send(message))
broadcast_alert([EmailAlert(), SMSAlert(), PushAlert()], "Server maintenance scheduled tonight.")
Output:
Email sent: Server maintenance scheduled tonight.
SMS sent: Server maintenance scheduled tonight.
Push notification sent: Server maintenance scheduled tonight.
Real-Time Example 6: Database Connectors
Switch between MySQL and PostgreSQL database connectors dynamically using polymorphic method calls.
Python
class MySQLDatabase:
def connect(self): return "Connecting to MySQL server..."
class PostgreSQLDatabase:
def connect(self): return "Connecting to PostgreSQL server..."
def initialize_db(db_driver):
print(db_driver.connect())
initialize_db(MySQLDatabase())
initialize_db(PostgreSQLDatabase())
Output:
Connecting to MySQL server...
Connecting to PostgreSQL server...
Real-Time Example 7: Custom String Formatting (__str__)
Implement
__str__ across different entity classes to return custom string representations polymorphically.
Python
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return f"Book: '{self.title}' by {self.author}"
class Movie:
def __init__(self, title, director):
self.title = title
self.director = director
def __str__(self):
return f"Movie: '{self.title}' directed by {self.director}"
items = [Book("Python Programming", "Guido van Rossum"), Movie("Inception", "Christopher Nolan")]
for item in items:
print(item) # Polymorphic print call
Output:
Book: 'Python Programming' by Guido van Rossum
Movie: 'Inception' directed by Christopher Nolan
Real-Time Example 8: Simulating Method Overloading via Default Arguments
Python doesn't support traditional method overloading natively, but default parameters allow methods to accept varying argument counts.
Python
class Calculator:
def add(self, a, b, c=0):
return a + b + c
calc = Calculator()
print("Sum of 2 numbers (10 + 20):", calc.add(10, 20))
print("Sum of 3 numbers (10 + 20 + 30):", calc.add(10, 20, 30))
Output:
Sum of 2 numbers (10 + 20): 30
Sum of 3 numbers (10 + 20 + 30): 60
Real-Time Example 9: File Reader Format Handler
Parse different file formats (JSON and CSV) polymorphically using a unified reader interface.
Python
class JSONReader:
def read_file(self, filepath):
return f"Parsing JSON configuration file: {filepath}"
class CSVReader:
def read_file(self, filepath):
return f"Parsing CSV spreadsheet file: {filepath}"
def load_data_source(reader, file_path):
print(reader.read_file(file_path))
load_data_source(JSONReader(), "config.json")
load_data_source(CSVReader(), "sales_report.csv")
Output:
Parsing JSON configuration file: config.json
Parsing CSV spreadsheet file: sales_report.csv