Stop 07 · Object-Oriented ProgrammingTopics · 6/10

Polymorphism & Duck Typing

Part of the Python Roadmap

In short

Polymorphism lets one piece of code work with many different kinds of objects. Write pay(method) once, and it works for UPI, card or cash, without a single if-else on the type.

Polymorphism means different classes can be used through the same method name. Python uses duck typing: if an object has the method you call, it works, whatever its class is.

The jaadu hosts a small stage show where a singer, a dancer and a magician each perform their own act after one wave of the jaadu's hand.

Think of it like this

If it quacks like a duck

At a talent show, the host just says 'perform!'. The singer sings, the dancer dances, the magician pulls a rabbit from a hat. The host doesn't need to know who's who, only that everyone can perform. Python works the same way: if an object has the method you call, it works.

Watch it happen

One call, three different behaviours

checkout()
UPI
Card
Cash

pay(499)

1/4checkout calls pay() on a UPI object. It sends a collect request.

The big ideas

What you need to know

Same name, different behaviour

Many classes can define a method with the same name. The right version runs based on the object.

Duck typing

Python doesn't care about the class, only that the method exists. Unrelated classes can be used interchangeably.

No type checks needed

Replace long if isinstance(...) chains with a method each class implements.

Easy to extend

Add a new WalletPay class with a pay() method and existing checkout code works with it, unchanged.

See it in code

Walk through the code

python
1class UPI:2    def __init__(self, vpa: str):3        self.vpa = vpa4 5    def pay(self, amount: float) -> str:6        return f"Collect request of Rs {amount} sent to {self.vpa}"7 8class Card:9    def __init__(self, last4: str):10        self.last4 = last411 12    def pay(self, amount: float) -> str:13        return f"OTP sent for Rs {amount} on card ending {self.last4}"14 15class Cash:16    def pay(self, amount: float) -> str:17        return f"Collect Rs {amount} at delivery"18 19def checkout(method, amount: float) -> None:20    print(method.pay(amount))21 22for m in [UPI("neha@okbank"), Card("4321"), Cash()]:23    checkout(m, 499)24 25print(len("hello"), len([1, 2, 3]), len({"a": 1}))

1/6UPI has a pay() method that uses its VPA.

Three unrelated payment classes, one checkout function. The built-in len() is polymorphic too.

Save yourself the pain

Common mistakes

Oops

Writing if type(m) == UPI: ... elif type(m) == Card: ... inside checkout.

Do this instead

Give every class a pay() method and just call m.pay(). Adding a new type then needs no edits to checkout.

Oops

Assuming objects must share a parent class to be used the same way.

Do this instead

In Python, a matching method is enough. Use an abstract base class only when you want to enforce it.

Your mission

Notification senders

~20 min

Quick check

What does duck typing mean in Python?

Go deeper

  1. 1Give Dog and Cat classes a speak() method and call it in one loop.
  2. 2Write a function that works with any object that has a read() method.
  3. 3Compare duck typing with checking isinstance() everywhere.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge