Polymorphism
Polymorphism means 'many forms'. Different classes can implement the same interface, and the correct method is called based on the object type at runtime.
15 min•By Priygop Team•Updated 2026
Polymorphism
Polymorphism
# Duck typing — if it walks like a duck...
class Duck:
def speak(self): return "Quack!"
def swim(self): return "Swimming..."
class Person:
def speak(self): return "Hello!"
def swim(self): return "Doing the backstroke..."
# Both have speak() and swim() — polymorphism!
def interact(entity):
print(entity.speak())
print(entity.swim())
interact(Duck())
interact(Person())
# Operator overloading
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
def __len__(self):
return int((self.x**2 + self.y**2) ** 0.5)
v1 = Vector(3, 4)
v2 = Vector(1, 2)
v3 = v1 + v2
print(f"{v1} + {v2} = {v3}")
print(f"Length of {v1}: {len(v1)}")Tip
Tip
Python uses duck typing: if it has speak() and swim(), it works — no interface declaration needed. 'If it quacks like a duck...'
Diagram
Loading diagram…
Inheritance lets child classes reuse parent code
Common Mistake
Warning
Assuming objects must share a parent class for polymorphism. In Python, any object with the right methods works (duck typing).
Practice Task
Note
(1) Create two unrelated classes with the same method name. (2) Write a function that calls that method on both. (3) Implement __add__ for a Vector class.