Skip to the workspace
Pebellslearn by building
Objects  ›  Lesson

Polymorphism

Polymorphism 19 minPolymorphism means using the same operation with different kinds of objects, each supplying its own behavior.

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.

One arrow labelled a.monthly_fee() splitting into three boxes — Current returns 5.0, Savings returns 0.0, Student returns 1.0 — with no diamond/if-shape anywhere on the arrow, converging into one "total" box

Month-end billing

Every account gets charged its fee, and the bank now sells three products. Here's the loop most people write first:

python

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:

python

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:

python

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:

step through it
1class Account:
2 def __init__(self, balance):
3 self.balance = balance
4 
5 def monthly_fee(self):
6 return 5.0
7 
8 def after_fee(self):
9 return self.balance - self.monthly_fee()
10 
11class Savings(Account):
12 def monthly_fee(self):
13 return 0.0
14 
15for a in [Account(100), Savings(100)]:
16 print(a.after_fee())

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.

What does this print?
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.

What does this print?
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:

broken — fix it

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.

What does this print?
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.0
  • monthly_run(["current", "student", "student"]) → 7.0
  • monthly_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.

Your task
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 2 decimals. Example: monthly_run(["current", "student"]) → 6.0.

Practice — level up

0/5 solved

Solve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.

Warm-upThe parent runs the child's code

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.

polymorphismoverride
DrillA loop with no branches

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.

polymorphismcomprehension
BuildTwo strangers, one call

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.

polymorphismduck-typing
BossRetire the if/elif chain

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.

polymorphismdispatchdictionaries
CapstoneA statement that renders itself

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.

polymorphismdispatchloop
Project context and further resources
You're building a piece ofA bank account that can't go wrong
This piece — monthly_run(): Every product prices itself, so month end has no if/elif chain to edit.
Scenario Month end, and the bank charges every account its fee. Next quarter there will be a fourth product — and the billing loop must not need editing when it arrives.
monthly_run.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
monthly_run(kinds) → floatCharge each account its own fee; return the total.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.