🔄 Polymorphism

Last Updated: 06 Sept 2025


Polymorphism = "Many Forms"

  • Same function/method name but different behavior depending on object or situation.
  • Python hae a MRO (Method Resolution Order) that determines the order in which methods are called
  • If a child class has a method with the same name as a parent class, the child class method will be called.
  • If a parent class has a method with the same name as a child class, the parent class method will be called.
  • You can use ClassName.mro() to see the method resolution order or use help(ClassName) function.

Hinglish Tip 🗣: Ek word "run()" → Dog run kare to alag, Car run kare to alag.


✏ Types of Polymorphism in Python

  1. Method Overriding → Same method in parent & child class (Inheritance).
  2. Method Overloading → Same method with different parameters (Python me directly nahi, but default args se possible hai).
  3. Operator Overloading → Using operators (+, *, etc.) with user-defined meaning.

💡 1. Method Overriding

class Animal:
    def sound(self):
        print("Animal makes a sound")

class Dog(Animal):
    def sound(self):   # overriding parent method
        print("Dog barks")

a = Animal()
a.sound()   # Animal makes a sound

d = Dog()
d.sound()   # Dog barks (overridden)
print(Dog.mro())
print(help(Dog))

💡 2. Method Overloading

👉 Python does not support traditional overloading (like Java/C++).But we can achieve it using default arguments.

class Math:
    def add(self, a=0, b=0, c=0):
        return a + b + c

m = Math()
print(m.add(5, 10))     # 15
print(m.add(2, 3, 4))   # 9
print(m.add())          # 0

👉 We can also use *args and **kwargs to handle variable number of arguments.


💡 3. Operator Overloading

Python allows us to change meaning of operators using dunder methods (like add, sub).

Example 1:

class Book:
    def __init__(self, pages):
        self.pages = pages

    def __add__(self, other):   # Overloading +
        return self.pages + other.pages

b1 = Book(100)
b2 = Book(200)
print(b1 + b2)   # 300 (total pages)

Example 2:

class MyList:
    def __init__(self, data):
        self.data = data

    def __len__(self):
        return len(self.data)

ml = MyList([1,2,3,4])
print(len(ml))   # 4

Example 3:

class Student:
    def __init__(self, name, marks):
        self.name = name
        self.marks = marks

    def __eq__(self, other):
        return self.marks == other.marks

s1 = Student("Amit", 85)
s2 = Student("Rahul", 85)
s3 = Student("Neha", 90)

print(s1 == s2)  # True
print(s1 == s3)  # False

💡 Quick Practice