In Python, polymorphism means calling the same method or built-in function on different objects and getting behavior tailored to each object. Inheritance is one way to achieve this: child classes inherit from a parent class and override methods when needed, while Python also supports duck typing, dunder protocols, operator overloading, and abstract base classes.
The PyTutorial Python Polymorphism Examples guide demonstrates these patterns with runnable code examples. Below is a structured learning path built around that resource so you can move from basic object behavior to enforceable interfaces and clean refactoring.
Step-by-Step Learning Path
- Grasp behavioral polymorphism via duck typing: Start with the core idea in the PyTutorial Python Polymorphism Examples guide: Python checks whether an object supports the method or operation you call rather than enforcing a rigid class hierarchy first.
class Dog: def speak(self): return "Woof" class Robot: def speak(self): return "Beep boop" for actor in (Dog(), Robot()): print(actor.speak()) - Practice method overriding with inheritance: Move into parent-child class hierarchies where subclasses redefine a shared method. In the PyTutorial Python Polymorphism Examples guide,
SquareandCircleeach implementarea()differently while a single loop callsshape.area()across both.
- Prefer explicit errors (
NotImplementedError) or clear base defaults over silent placeholder returns that can hide missing implementations. - Keep method names and parameter signatures consistent across subclasses so callers do not need special-case branches.
Use dunder methods for protocol-based polymorphism:
Explore polymorphism without shared inheritance by implementing special ("dunder") methods such as__len__(). Just as built-inlen()works across lists, tuples, strings, and dictionaries, custom classes likePlaylistorTeamcan supportlen(obj)by defining__len__(self).Apply operator overloading with care:
Learn how syntax operators map to underlying methods—such as__add__(self, other)for+—as shown withVectoraddition in the PyTutorial Python Polymorphism Examples guide.
- Keep overloaded operators intuitive for the domain (for example, combining two vectors).
- Avoid surprising behavior that makes code harder for teammates or your future self to read.
Enforce contracts with abstract base classes:
When loose duck typing risks incomplete subclasses in larger codebases, use Python'sabcmodule (ABCand@abstractmethod). Attempting to instantiate a subclass that leaves an abstract method unimplemented raises aTypeErrorearly rather than failing later at runtime.Refactor conditional chains into polymorphic types:
Apply the practical takeaway from the PyTutorial Python Polymorphism Examples guide: replace repeatedif/eliftype or mode checks (such as payment methods or processors) with interchangeable classes that expose a shared interface.
Summary Comparison of Polymorphism Patterns
| Pattern | Shared Base Class Required? | When It Fits Best | Trade-off |
|---|---|---|---|
| Duck typing | No | Lightweight scripts and flexible object collections | Missing methods fail only when called |
| Inheritance + overriding | Yes | Related domain models sharing common state or behavior | Tighter coupling if hierarchies grow deep |
| Dunder protocols | No | Integrating custom types with built-in syntax/functions (len, iteration, etc.) | Requires knowing standard Python data model hooks |
| Operator overloading | No | Math, coordinates, or value types where symbols are natural | Overuse can obscure intent |
Abstract base classes (abc) | Yes (ABC) | Frameworks, plugins, or teams needing upfront interface checks | Extra boilerplate compared to plain duck typing |
Practice Checklist
- Write two unrelated classes sharing a
render()orrun()method and iterate over both in one loop. - Build a small base class with two subclasses overriding a calculation method, then test
NotImplementedErroron an unimplemented method. - Implement
__len__()on a custom container class and verifylen()works on it. - Replace one multi-branch
if/elifblock in an existing project with a polymorphic class map.
