Polymorphism
Shelfwise's delivery estimate began as one line. Then e-books arrived, then gift cards, then audiobooks, and now delivery_days(item) is a ladder of isinstance checks that someone must extend, carefully, every time a new product appears. Polymorphism deletes the ladder.
The rule
One call, many shapes — let the object decide.
Polymorphism means the same call works on different kinds of object, and each one answers in its own way.
# Before: the caller decides by checking types
def delivery_days(item):
if isinstance(item, EBook):
return 0
elif isinstance(item, GiftCard):
return 1
else:
return 3
# After: each class answers for itself
class Product:
def delivery_days(self):
return 3
class EBook(Product):
def delivery_days(self):
return 0
class GiftCard(Product):
def delivery_days(self):
return 1
latest = max(item.delivery_days() for item in cart)The caller writes item.delivery_days() once. At run time, the object's own class picks which version runs. Adding AudioBook means writing one new class; no existing function gets a new elif.
Polymorphism does not require inheritance. Python uses duck typing: if an object has a delivery_days() method, you can call it, whatever its class. Java and C# get the same effect through interfaces, where unrelated classes promise the same method.
You already use polymorphism every day. len() works on a list, a string and a dictionary, and each type supplies its own answer through a special method called __len__. len never checks what it was given; it just asks. Your Shelfwise classes can offer the same courtesy to the code that uses them.
This is also where the other pillars pay off. Encapsulation keeps each object's rules inside it, abstraction gives every product the same simple interface, inheritance can share defaults, and polymorphism lets one piece of code treat them all alike.