Part 09 / Topic 7 of 12
Polymorphism and duck typing
Polymorphism ("many forms") means different classes have a method with the same name, so one piece of code can work with all of them. Duck typing: "if it walks like a duck and quacks like a duck, it is a duck". Python does not check the class. It only checks that the object has the method you call.
Think of a "Pay" button at a shop counter: UPI, card or cash all respond to "pay", each in its own way.
Real-world example: different ways to pay.
class UpiPayment:
def pay(self, amount: int) -> str:
return f"Paid ₹{amount:,} by UPI"
class CardPayment:
def pay(self, amount: int) -> str:
return f"Paid ₹{amount:,} by card (+2% fee: ₹{amount * 0.02:,.2f})"
class GiftVoucher: # not related to the others at all
def pay(self, amount: int) -> str:
return f"Paid ₹{amount:,} with a gift voucher"
def checkout(method, amount: int) -> None:
print(method.pay(amount)) # works for anything that has .pay()
for method in [UpiPayment(), CardPayment(), GiftVoucher()]:
checkout(method, 1500)
Output:
Paid ₹1,500 by UPI
Paid ₹1,500 by card (+2% fee: ₹30.00)
Paid ₹1,500 with a gift voucher
The three classes share no parent. checkout works because each one "quacks" (has pay).
You already know built-in polymorphism: len("hello"), len([1, 2]) and len({"a": 1}) all work on different types.
🔍 Going deeper: if an object lacks the method, you get
AttributeErrorat the moment of the call. EAFP from Part 6 fits duck typing well: just call it and catch the error if needed.
Done here? The practice set for Part 9 — 8 exercises with solutions — is on the part page.