Lesson

Python Polymorphism

10 min reading
Free Course

Python Polymorphism: Duck Typing, Overrides, and Protocols

Polymorphism means one interface or function works cleanly across different data types and classes. Built-in functions like len() are polymorphic: len("abc"), len([1, 2]), and len({"a": 1}) all work because each type implements __len__().

Python relies on duck typing ("if it walks like a duck and quacks like a duck, treat it as a duck"). As long as an object provides the expected method, Python does not require a shared base class.

Polymorphism via Method Overriding and Duck Typing

Different payment providers can share the same charge(amount) method name so checkout logic handles them uniformly without if/elif chains.

class CardGateway:
    def charge(self, amount: float) -> str:
        return f"Charged ${amount:.2f} via Card"

class WalletGateway:
    def charge(self, amount: float) -> str:
        return f"Charged ${amount:.2f} via Digital Wallet"

def process_order(gateway, total: float) -> None:
    print(gateway.charge(total))

for provider in (CardGateway(), WalletGateway()):
    process_order(provider, 49.0)

Static Duck Typing with typing.Protocol

If you use type hints, typing.Protocol defines an interface contract structurally—classes satisfy it automatically simply by defining matching methods without inheriting from anything.

Common Mistakes to Avoid

  • Writing if isinstance(x, ...) chains everywhere: Checking concrete types defeats polymorphism; call the shared method directly instead.
  • Changing method signatures in child classes: If a parent defines save(self, path: str), a subclass defining save(self) breaks callers expecting polymorphism.
  • Overengineering class hierarchies: Don't force unrelated classes into an artificial parent class when duck typing or Protocol keeps them decoupled.

Frequently Asked Questions

Does Python support method overloading by argument type like Java?

No. Defining two methods with the same name in a Python class overwrites the first one. Use default arguments, *args, or @functools.singledispatch instead.

What is operator overloading in Python?

Classes can implement dunder methods like __add__ or __eq__ so operators like + and == work polymorphically on custom objects.

How does Protocol differ from abc.ABC?

abc.ABC requires explicit inheritance (class Card(Gateway)), whereas Protocol validates structural compatibility statically without requiring inheritance.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
Python Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum