Python Polymorphism
Polymorphism means the same operation or method name can work on objects of different types, each responding in its own way.
The word polymorphism means "many forms." In programming it describes code that treats different kinds of objects through a common interface. As long as each object provides the method being called, the calling code does not need to know or care which exact class it is dealing with. This makes programs flexible and easy to extend with new types.
The same method name on different classes
Suppose several unrelated classes each define a method called speak. A single loop can call speak on every object, and each responds appropriately. The loop stays the same even if you add more animal classes later.
One loop, many behaviors
class Dog:
def speak(self):
return "Woof"
class Cat:
def speak(self):
return "Meow"
class Duck:
def speak(self):
return "Quack"
for animal in [Dog(), Cat(), Duck()]:
print(animal.speak()) # Woof, Meow, QuackPolymorphism through inheritance
Polymorphism often works together with inheritance. Subclasses override a shared method from a common parent, and code written against the parent type still calls the correct overridden version at runtime.
Overridden methods resolved at runtime
class Shape:
def area(self):
return 0
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14159 * self.radius ** 2
shapes = [Square(4), Circle(3)]
for s in shapes:
print(round(s.area(), 2)) # 16, 28.27- Polymorphism lets one interface serve many object types.
- Different classes can share a method name and behave differently.
- It pairs naturally with inheritance and method overriding.
- Python's duck typing focuses on behavior, not the exact class.
Exercise: Python Classes
What is the purpose of the `__init__` method in a class?