Polymorphism
Polymorphism is using one call site with many types: shape.area() works for a circle or a rectangle because each type supplies its own area. In Python this is usually duck typing plus inheritance, not a compiler-checked interface.
Detailed Explanation
A function that accepts "something with read()" is polymorphic. It does not name File. It calls read. A file, a socket wrapper, and a io.StringIO all work. That is duck typing, and it is the everyday polymorphism of Python.
Inheritance gives you a second, nominal form. If PriorityOrder is an Order, a function typed or documented as accepting Order can receive either. The method that runs is the subclass's override. That is subtype polymorphism, the same idea as Java's virtual methods.
Python also has operator polymorphism. + is __add__ on the left operand, or __radd__ on the right. len is __len__. The builtin looks for a method, not a specific class. You plug into that system by implementing the dunder, not by subclassing list unless you need to be a list.
What Python does not have is Java-style overload resolution on argument types. def send(x: int) and def send(x: str) cannot both exist as two functions. The second definition replaces the first. You write one function and branch, or you dispatch on a singledispatch generic, or you use different names.
Checkers add a third layer. A Protocol is a structural type: any object with the right methods matches. An ABC with @abstractmethod is a nominal type you inherit. Both document polymorphism for tools; only the ABC (and @runtime_checkable protocols) participate in isinstance the way you expect.
Prefer polymorphism over if isinstance chains when the set of types will grow. Prefer a simple if when there are two cases and they will stay two cases. A match on type is an isinstance chain with nicer syntax, not a substitute for a method on the objects.
Code Examples
class Circle:
def __init__(self, radius: float):
self.radius = radius
def area(self) -> float:
return 3.1416 * self.radius ** 2
class Rectangle:
def __init__(self, width: float, height: float):
self.width = width
self.height = height
def area(self) -> float:
return self.width * self.height
def total_area(shapes: list) -> float:
return sum(shape.area() for shape in shapes)
print(total_area([Circle(1), Rectangle(2, 3)])) # 9.1416# Builtin polymorphism: len and + dispatch on the type.
print(len("ada"), len([1, 2, 3])) # 3 3
print("a" + "b", [1] + [2]) # ab [1, 2]Common Gotchas
Two `def send` in one class do not overload
the second replaces the first. Use a different name or a single function with branching.
`isinstance` chains rot
every new type visits every chain. Put the behaviour on the type (or a protocol) instead.
Polymorphism hides the concrete type
that is the point, and it makes "only Circle is slow" harder to see. Profile the call, not the name in the source.
`super()` is how an override reuses the parent
without it you replaced, not extended.