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.
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)
typing.ProtocolIf you use type hints, typing.Protocol defines an interface contract structurally—classes satisfy it automatically simply by defining matching methods without inheriting from anything.
if isinstance(x, ...) chains everywhere: Checking concrete types defeats polymorphism; call the shared method directly instead.save(self, path: str), a subclass defining save(self) breaks callers expecting polymorphism.Protocol keeps them decoupled.No. Defining two methods with the same name in a Python class overwrites the first one. Use default arguments, *args, or @functools.singledispatch instead.
Classes can implement dunder methods like __add__ or __eq__ so operators like + and == work polymorphically on custom objects.
Protocol differ from abc.ABC?abc.ABC requires explicit inheritance (class Card(Gateway)), whereas Protocol validates structural compatibility statically without requiring inheritance.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.