Polymorphism in Practice
Bringing together everything from this week into a real-world project.
Project: Notification System
Imagine you are building an app that sends notifications through different channels -- email, SMS, and push notifications. Each channel sends differently, but the rest of your code should not care which one it is using. This is polymorphism in action.
class Notification:
def __init__(self, recipient, message):
self.recipient = recipient
self.message = message
def send(self):
raise NotImplementedError("Subclasses must implement send()")
def __str__(self):
return f"To: {self.recipient} | {self.message}"
class EmailNotification(Notification):
def send(self):
print(f"Sending EMAIL to {self.recipient}: {self.message}")
class SMSNotification(Notification):
def send(self):
print(f"Sending SMS to {self.recipient}: {self.message}")
class PushNotification(Notification):
def send(self):
print(f"Sending PUSH to {self.recipient}: {self.message}")
Polymorphism in Action
# Create different notification types
notifications = [
EmailNotification("alice@email.com", "Your order shipped!"),
SMSNotification("+1234567890", "Your OTP is 4521"),
PushNotification("bob_device", "New message received")
]
# Polymorphism: same loop, different behavior
for n in notifications:
n.send() # Each sends differently
print(n) # __str__ works for all
Output:
Sending EMAIL to alice@email.com: Your order shipped!
To: alice@email.com | Your order shipped!
Sending SMS to +1234567890: Your OTP is 4521
To: +1234567890 | Your OTP is 4521
Sending PUSH to bob_device: New message received
To: bob_device | New message received
Why This Design is Powerful
- Method overriding: Each subclass overrides
send()with its own logic. - Operator overloading:
__str__makesprint()work beautifully for all types. - Single interface: The loop does not know or care which type each notification is.
- Easy to extend: Adding a new channel (e.g., SlackNotification) requires zero changes to existing code.
Bonus: Shape Calculator with Operator Overloading
Combining method overriding (for area()) with operator overloading (for + and print()).
class Shape:
def area(self):
return 0
def __add__(self, other):
total = self.area() + other.area()
return f"Combined area: {total:.2f}"
def __str__(self):
return f"{self.__class__.__name__}: area = {self.area():.2f}"
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14159 * self.radius ** 2
class Rectangle(Shape):
def __init__(self, w, h):
self.w = w
self.h = h
def area(self):
return self.w * self.h
# Polymorphism + operator overloading
c = Circle(5)
r = Rectangle(4, 6)
print(c) # Circle: area = 78.54
print(r) # Rectangle: area = 24.00
print(c + r) # Combined area: 102.54
Week 5 Recap
5.1 What is Polymorphism?
Same method name, different behavior depending on the object.
5.2 Method Overriding in Depth
Complete vs partial overrides using super() in inheritance hierarchies.
5.3 Operator Overloading
Dunder methods let you define how +, ==, print(), and len() work.
5.4 Duck Typing
Python cares about methods, not class types -- no inheritance needed.
Best Practices
- Design your parent class with a clear interface that all children will follow.
- Use
raise NotImplementedErrorin the parent to enforce that children must override critical methods. - Always define
__str__to make your objects printable and debuggable.
Common Mistakes
- Forgetting to override a required method -- the parent's
NotImplementedErrorwill catch this at runtime. - Using if/elif chains to check types instead of letting polymorphism handle the differences.
- Making subclass methods return different types than the parent -- keep the contract consistent.
Practice Exercises
Exercise 1: Add SlackNotification
Extend the Notification System with a SlackNotification class. Override send() to print "Sending SLACK to #channel: message". Add it to the notifications list and verify it works without changing any existing code.
Exercise 2: Vehicle Fleet
Create a Vehicle base class with fuel_cost(distance), __str__, and __lt__ (compare by fuel efficiency). Create Car, Truck, and Motorcycle subclasses. Calculate the total fuel cost for a fleet traveling 100km.
Exercise 3: Full Shape System
Build a complete Shape system with Circle, Rectangle, and Triangle. Include area(), perimeter(), __str__, __add__ (combine areas), and __lt__ (compare by area). Sort a list of mixed shapes by area.
Summary
- Polymorphism lets you write code that works with any object that follows the expected interface.
- Method overriding, operator overloading, and duck typing are all forms of polymorphism.
- Real systems like notification dispatchers and shape calculators rely on polymorphism daily.
- Design for extension: new subclasses should work without changing existing code.
What's Next?
In Week 6, we explore Abstraction -- the art of hiding complexity and exposing only what is needed. You will learn about abstract classes, interfaces, multiple inheritance, and the famous diamond problem. See you there.