Polymorphism means same function name, different behaviors, depending on class or input.
Two types in Python:
Type
Meaning
Compile-time (Overloading)
Same function, different parameters (simulated in Python)
Runtime (Overriding)
Child class modifies parent method
Method Overriding (Runtime Polymorphism)
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Dog barks")
class Cat(Animal):
def speak(self):
print("Cat meows")
for pet in [Dog(), Cat()]:
pet.speak()
Each object responds differently to the same speak() call.
Method Overloading (Simulated)
class Math:
def add(self, a, b, c=None):
if c:
return a + b + c
return a + b
m = Math()
print(m.add(1, 2))
print(m.add(1, 2, 3))
Python doesnβt support true overloading, so we use default parameters.
Polymorphism with Functions & Objects
class Car:
def move(self):
print("Car is driving")
class Plane:
def move(self):
print("Plane is flying")
def operate(vehicle):
vehicle.move()
operate(Car())
operate(Plane())
Same function β different behavior based on object type.
Polymorphism with Inheritance
class Shape:
def area(self):
raise NotImplementedError("Subclass must implement this")
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
return 3.14 * self.r * self.r
for s in [Square(4), Circle(5)]:
print(s.area())
Child classes provide unique logic for inherited structure.
Real-World Example (Combined)
class User:
def login(self):
print("Login from User")
class Admin(User):
def login(self):
print("Admin login with security check")
class Customer(User):
def login(self):
print("Customer login")
users = [Admin(), Customer(), User()]
for u in users:
u.login()
Explanation
Admin & Customeroverride the login() method.
Same method name β different behaviors based on object type.