Python Notes
Understand polymorphism in Python — method overriding, duck typing, operator overloading, runtime polymorphism, and how to write flexible, reusable code with real-world examples.
🧠 Real-World Analogy — Remote Control
Think of a remote control's "Volume Up" button. Press it on a TV, volume increases. Press it on an AC, temperature increases. Press it on a music player, song volume increases. Same button, different behavior depending on the device. Same interface, different behavior — yahi Polymorphism hai. In Greek: *poly* = many, *morph* = forms. "One name, many forms."
1️⃣ Method Overriding (Runtime Polymorphism)
Output:
2️⃣ Duck Typing
In Python, duck typing means: "If an object walks like a duck and quacks like a duck, then we treat it as a duck." Meaning: No type check is needed — if the object has the required method, it will work.
Output:
| Dog | 'Woof!' — runs on 4 legs |
| Cat | 'Meow!' — slinks quietly |
| Robot | 'Beep boop!' — rolls on wheels |
| Human | 'Hello!' — walks on 2 legs |
3️⃣ Polymorphism with Built-in Functions
4️⃣ Payment Gateway — Real-World Polymorphism
Output:
| 🧾 Receipt | ₹999.00 via CreditCard |
| 🧾 Receipt | ₹999.00 via UPI |
| 🧾 Receipt | ₹999.00 via NetBanking |
| 👛 Wallet 'Paytm' payment ₹999.00 | Remaining | ₹501.00 |
| 🧾 Receipt | ₹999.00 via Wallet |
| ❌ Insufficient wallet balance! (Balance | ₹501.00) |
5️⃣ Operator Overloading
In Python, we can give new meaning to operators like+,-,*,==,<for our own classes — this is also polymorphism.
class Vector:
def __init__(self, x, y, z=0):
self.x, self.y, self.z = x, y, z
def __add__(self, other): # v1 + v2
return Vector(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other): # v1 - v2
return Vector(self.x - other.x, self.y - other.y, self.z - other.z)
def __mul__(self, scalar): # v1 * 3
return Vector(self.x * scalar, self.y * scalar, self.z * scalar)
def __rmul__(self, scalar): # 3 * v1
return self.__mul__(scalar)
def __eq__(self, other): # v1 == v2
return self.x == other.x and self.y == other.y and self.z == other.z
def __abs__(self): # abs(v1) → magnitude
import math
return math.sqrt(self.x**2 + self.y**2 + self.z**2)
def __str__(self):
return f"Vector({self.x}, {self.y}, {self.z})"
def __repr__(self):
return f"Vector(x={self.x}, y={self.y}, z={self.z})"
def dot(self, other):
return self.x*other.x + self.y*other.y + self.z*other.z
v1 = Vector(1, 2, 3)
v2 = Vector(4, 5, 6)
print(f"v1 = {v1}")
print(f"v2 = {v2}")
print(f"v1 + v2 = {v1 + v2}")
print(f"v2 - v1 = {v2 - v1}")
print(f"v1 * 3 = {v1 * 3}")
print(f"2 * v2 = {2 * v2}")
print(f"|v1| = {abs(v1):.4f}")
print(f"v1 == v1 = {v1 == v1}")
print(f"v1 == v2 = {v1 == v2}")
print(f"v1 · v2 = {v1.dot(v2)}")Output:
6️⃣ Polymorphism with str(), len(), repr()
class Playlist:
def __init__(self, name):
self.name = name
self.songs = []
def add(self, song):
self.songs.append(song)
def __len__(self): # len(playlist)
return len(self.songs)
def __str__(self): # str(playlist) / print(playlist)
return f"Playlist '{self.name}' ({len(self)} songs)"
def __repr__(self):
return f"Playlist(name={self.name!r}, songs={self.songs!r})"
def __contains__(self, song): # "song" in playlist
return song in self.songs
def __iter__(self): # for song in playlist:
return iter(self.songs)
p = Playlist("Bollywood Hits")
p.add("Kal Ho Na Ho")
p.add("Tum Hi Ho")
p.add("Raabta")
print(p) # uses __str__
print(len(p)) # uses __len__
print("Raabta" in p) # uses __contains__
print(repr(p)) # uses __repr__
print("\nTracklist:")
for i, song in enumerate(p, 1):
print(f" {i}. {song}")Output:
🇮🇳 Hindi Explanation (हिंदी में समझें)
Polymorphism kya hai? Polymorphism means "one interface, many implementations." Just as thearea()method exists in Circle, Rectangle, and Triangle — but each calculates differently. You can use a single loop to callarea()on any shape without knowing the specific type.
Duck Typing kya hai? In Python, there's no need to explicitly check types. If an object has the method you need, it will work. "If it talks like a duck and walks like a duck, it's a duck."
Operator Overloading kya hai? Giving operators like+,-,*,==new meaning for your own class. This makes your code more readable and natural (like Vector addition in math).
❓ Interview Questions
Q1: What is polymorphism? Give a real-world example.
Answer: Polymorphism means "many forms" — the same interface behaves differently based on the object type. Real-world: A draw() method on Circle, Rectangle, and Triangle each draws a different shape. In code, you can loop over all shapes and call draw() without knowing the specific type.
Q2: What is duck typing? How is it different from Java's approach?
Answer: Duck typing means Python doesn't require formal type checking — if an object has the required method/attribute, it works. In Java, you must explicitly implement an interface. Python's approach is more flexible and concise. The downside: runtime errors instead of compile-time errors.
Q3: What is the difference between method overriding and method overloading?
Answer:
- Overriding: A subclass provides its own implementation of a method already defined in the parent. Runtime polymorphism.
- Overloading: Same method name with different parameters. Python does NOT support traditional overloading — use default/
*argsinstead.
Q4: How does Python implement operator overloading?
Answer: Via dunder (magic) methods: __add__ for +, __mul__ for *, __eq__ for ==, __lt__ for <, etc. When Python sees a + b, it calls a.__add__(b).
Q5: What is the Open/Closed Principle and how does polymorphism enable it?
Answer: The Open/Closed Principle (SOLID) says: "Open for extension, closed for modification." Polymorphism enables this — you can add a new PaymentMethod subclass without changing the checkout() function. The function works with any payment method that implements pay().
Q6: Can you use isinstance() to check polymorphic types?
Answer: Yes, and it's the preferred way in Python:
if isinstance(obj, PaymentMethod):
obj.pay(amount)isinstance() returns True for the class AND all subclasses, making it ideal for polymorphic dispatch.
🧪 Practice Exercises
- Animal Choir: Create
Animalhierarchy withDog,Cat,Parrot,Cow. Write amake_all_speak(animals)function. - Notification System: Create
NotificationChannel(abstract) withEmail,SMS,PushNotificationsubclasses each implementingsend(message). - Fraction Math: Create a
Fractionclass with__add__,__sub__,__mul__,__truediv__,__eq__,__str__. - Shipping Calculator: Create
ShippingMethod(Standard, Express, Overnight) with polymorphiccalculate_cost(weight, distance). - File Exporter: Create
Exporterbase class withCSV,JSON,XMLsubclasses implementingexport(data, filename).
💡 Next Topic → Encapsulation: Learn to hide internal details, use private/protected attributes, getters/setters, and Python's @property decorator.Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Polymorphism in Python.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, object, oriented, programming
Related Python Master Course Topics