The term Polymorphism is derived from Greek words meaning "having multiple forms". In software architecture and Object-Oriented Programming, polymorphism allows different classes to expose the same interface (method signatures) while providing distinct, specialized implementations behind the scenes.
1. What is Polymorphism?
Polymorphism allows code to treat diverse object types uniformly. Instead of checking an object's exact type with long chains of if/elif statements, client code simply invokes a standard method name, and Python executes the version specific to that object.
1classDog:
2defspeak(self)->str:
3return"Woof!"
4
5classCat:
6defspeak(self)->str:
7return"Meow!"
8
9classCow:
10defspeak(self)->str:
11return"Moo!"
12
13# A polymorphic function: Works with ANY object providing a speak() method
Python is dynamically typed and adheres to the Duck Typing philosophy:
"If it walks like a duck and quacks like a duck, it's a duck."
In statically typed languages (like Java or C++), objects must typically inherit from a shared interface or abstract class to achieve polymorphism. In Python, objects don't need a shared ancestor class; as long as they implement the expected methods or attributes, they are valid candidates!
11print(f"Rendering video frames & audio: {filename}")
12
13deflaunch_media(player, media_file):
14# We do not check isinstance(player, ...); we just invoke .play()
15 player.play(media_file)
16
17launch_media(MP3Player(),"song.mp3")
18launch_media(VideoPlayer(),"movie.mp4")
3. Polymorphism in Class Hierarchies
When combined with class inheritance, polymorphism ensures that derived subclasses adhere to common parent contracts while delivering specialized behavior:
1import math
2
3classShape:
4defarea(self)->float:
5raise NotImplementedError("Subclasses must implement area()")
6
7defperimeter(self)->float:
8raise NotImplementedError("Subclasses must implement perimeter()")
3print(f"Processing ₹{amount:.2f} via UPI Instant Transfer.")
4
5classCreditCardPayment:
6defprocess_payment(self, amount:float):
7print(f"Processing ₹{amount:.2f} via Credit Card Gateway (2% fee).")
8
9classCryptoPayment:
10defprocess_payment(self, amount:float):
11print(f"Processing ₹{amount:.2f} via Blockchain Confirmation.")
12
13defcheckout(processor, total:float):
14# Polymorphic dispatch allows adding new processors without modifying checkout!
15 processor.process_payment(total)
16
17checkout(UPIPayment(),1499.00)
18checkout(CreditCardPayment(),4999.00)
⚠️ Common Intermediate Mistakes & Gotchas
1. Excessive isinstance() Checks
Writing cascades of if isinstance(obj, Cat): ... elif isinstance(obj, Dog): ... defeats polymorphism. Instead, define a common method (e.g., .speak()) on all classes and let duck typing handle execution.
2. Returning None from __str__() or __repr__()
Special methods like __str__() must return a string. Returning a non-string or printing inside the method causes a TypeError.
💻 Try It Yourself: Polymorphic Payment Processing
Scenario
Create a polymorphic payment system where different payment methods (CreditCardPayment, UPIPayment, CryptoPayment) implement a unified pay(amount) method.
Complete Solution
1classCreditCardPayment:
2def__init__(self, card_last4:str):
3 self.card_last4 = card_last4
4
5defpay(self, amount:float):
6print(f"Paid ₹{amount:,.2f} using Credit Card ending in {self.card_last4} (+2% surcharge).")
7
8classUPIPayment:
9def__init__(self, vpa:str):
10 self.vpa = vpa
11
12defpay(self, amount:float):
13print(f"Paid ₹{amount:,.2f} via UPI to {self.vpa} (Instant settlement).")
1Paid ₹4,500.00 using Credit Card ending in 8821 (+2% surcharge).
2Paid ₹1,200.00 via UPI to aarav@upi (Instant settlement).
Interactive Quiz• Knowledge Check
Practice Quiz
Question 1
What does "Duck Typing" mean in the context of Python polymorphism?
Question 2
Which dunder method is invoked when the + operator is used between two custom objects?
Question 3
What is the main architectural advantage of polymorphism in large software systems?
Question 4
What exception should base class placeholder methods raise to mandate child implementation?
Question 5
Which dunder method allows a custom class instance to be passed into Python's built-in len() function?
🚀 What's Next?
In the next lesson, we will continue your intermediate Python journey with Encapsulation and Abstraction (5: Object-Oriented Programming (Intermediate)).