Polymorphism means using the same operation with different kinds of objects, each supplying its own behavior.
Write callers that depend on a shared contract rather than selecting every implementation themselves.
The inheritance example showed a method being selected from an object's class. Now use that behavior to simplify a caller: one billing loop asks each product for its fee. Polymorphism is this ability to use the same operation with different implementations. The important question is what every implementation must promise so the loop's calculation remains valid.

Month-end billing
Every account gets charged its fee, and the bank now sells three products. Here's the loop most people write first:
It works. It's also the thing you'll be editing forever: every new product means finding this chain — and the four others like it scattered through the codebase — and adding a branch. Miss one and the product silently bills nothing.
Move the answer into the type instead, and the loop stops needing branches:
The expression inside sum calls monthly_fee() once for each account and adds
the returned amounts. It is a compact spelling of a loop with a running total.
Adding another compatible product does not require changing that summing logic.
Something must still create the new product and put it in accounts.
Preparing this topic’s interactive investigation…
Separate selecting a product from using it
External input usually contains names such as "student", not Python instances.
A factory—a function that builds an object—translates that input at one boundary:
The dictionary stores classes; the final () constructs the selected class.
Adding a product means updating that selection boundary as well as supplying the
class. The calculation stays unchanged because it depends on an operation, not
the product name. Unlike the first if chain, an unknown name here cannot silently
contribute zero: lookup raises. An API would translate that failure into its
chosen input error.
Now inspect the contract the summing code relies on:
| Promise | Compatible implementation | Failure that a method name alone misses |
|---|---|---|
| Called with no explicit arguments | monthly_fee(self) |
Requires an extra month argument. |
| Returns an amount | return 1.0 |
Prints 1.0 and returns None. |
| Uses the agreed unit | All fees in the same currency unit | Returns paise where callers expect rupees. |
| Computes a fee without charging it | Reads product policy | Deducts money each time a display asks for the fee. |
Python's dynamic call checks whether the operation can run; it does not prove the meaning of its result. The print-versus-return distinction is especially relevant: visible output cannot be added to a total.
To transfer this design, implement two shipping methods with quote(weight) in
the same currency unit. One charges a flat 40; the other charges 10 * weight.
Write one caller that requests both quotes for weights 0, 2, and 5. Then
add a third method without changing that caller. Keep construction separate, and
verify the original objects have not been charged or otherwise changed by asking
for a quote twice.
The parent calls down into the child
a.monthly_fee() is one line of source, but it isn't one piece of code.
Python looks the method up on the object in front of it, every single
time it runs — even when the calling code was written before the object's
class existed:
after_fee is written once, on the parent, and it existed before Savings
did — yet self.monthly_fee() finds the child's version when self is a
Savings. The parent calls down into code it has never heard of.
class Fee:
def amount(self):
return 5.0
def receipt(self):
return f"charged {self.amount()}"
class Free(Fee):
def amount(self):
return 0.0
print(Free().receipt())No shared parent required
Notice what the billing loop never did: check a type, or demand a common
application base class. Current, Savings and Student implicitly derive from
Python's object, but share no fee implementation through inheritance.
class Wallet:
def monthly_fee(self):
return 2.0
def total(items):
return sum(i.monthly_fee() for i in items)
class Voucher:
def monthly_fee(self):
return -1.0
print(total([Wallet(), Voucher()]))Inheritance can supply a shared method, but putting arbitrary objects in a list does not check that they support it. Duck typing means writing against the needed behavior; compatible arguments, results, and effects still matter.
Quick practice
In this fee loop, an exact type(...) check wrongly excludes a compatible
subclass. Type checks have legitimate uses, but this one contradicts the loop's
intended contract:
A student is being billed nothing. Make it print 6.0.
The repaired calculation needs no branch. Selecting classes from external names remains a separate concern, as the factory above demonstrated.
print(len("abc"), len([1, 2]), len({"a": 1, "b": 2, "c": 3}))🎯 Your turn
Define Current, Savings and Student, each with monthly_fee() returning
5.0, 0.0 and 1.0. Write monthly_run(kinds) which builds the matching
account for each name and returns the total fee, rounded to two decimals:
monthly_run(["current", "savings"])→5.0monthly_run(["current", "student", "student"])→7.0monthly_run([])→0
Hint — map the names to classes with a dict, then sum. The summing loop
should contain no if at all.
Press ▶ Run, try the Live App chips, then ✓ Check. After that, the
practice set below retires a real if/elif chain and puts your own types on
the receiving end of a built-in-style call.
Practice — level up
0/5 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Define Fee with amount() returning 5.0 and receipt() returning f"charged {self.amount()}". Define Free(Fee) overriding only amount() to return 0.0. Write receipt_for(kind) returning the receipt of a Free when kind is "free", otherwise of a Fee.
Define Current and Savings, each with monthly_fee() returning 5.0 and 0.0. Write fee_list(kinds) returning the fee of each named account, in order. The loop that collects the fees must not test the kind.
Define Email and SMS with no custom base class. Each has send(msg) returning "email: " and "sms: ". Write broadcast(msg) returning what both return, as a list, by looping over one of each.
Define Standard, Premium and Student, each with rate() returning 0.0, 0.02 and 0.01. Write charges(kinds, amount) returning amount * rate for each named product, each rounded to 2 decimals. Choose the class through a dict — there must be no if anywhere in the function.
Define Deposit, Withdrawal and Fee, each built from an amount, each with line() returning "+50" / "-20" / "fee 2" and effect() returning what it does to the balance (+amount, -amount, -amount). Write statement(entries, start) where entries look like [["deposit", 50], ["fee", 2]], returning {"lines": [...], "balance": ...} with the balance rounded to 2 decimals.