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.
Inheritance allows a class (child) to acquire properties and methods of another class (parent).
This promotes:
Code reusability
Hierarchy / structure
Cleaner and scalable programs
Basic Inheritance
class Animal:
def speak(self):
print("Animals make sound")
class Dog(Animal): # Dog inherits from Animal
pass
d = Dog()
d.speak()
Explanation
Animal is the parent/base class.
Dog is the child/derived class.
Dog gets the speak() method without writing it again.
Single Inheritance
class Parent:
def show(self):
print("This is parent class")
class Child(Parent):
def display(self):
print("This is child class")
c = Child()
c.show()
c.display()