What is Polymorphism ?

                Polymorphism means “many forms”.

                In Python OOP, polymorphism allows the same method or operation to behave differently based on the object or context.


Why Polymorphism is Needed ?

Polymorphism helps to:

  • write flexible code
  • reduce complexity
  • support extensibility
  • follow real-world behaviour

Types of Polymorphism :
  • Method Overriding
  • Method Overloading

Method Overriding :
                  When a child class provides its own implementation of a method defined in the parent class.

Example :

Python
class Animal: def speak(self): print("Animal makes a sound") class Dog(Animal): def speak(self): print("Dog barks") class Cat(Animal): def speak(self): print("Cat meows") a = Animal() d = Dog() c = Cat() a.speak() d.speak() c.speak() #output Animal makes a sound Dog barks Cat meows 



Method Overloading :
                  A function can work with different object types, as long as they support the required method.

Example :

Python
class Bird: def fly(self): print("Bird flies") class Airplane: def fly(self): print("Airplane flies") def make_fly(obj): obj.fly() make_fly(Bird()) make_fly(Airplane()) #output Bird flies Airplane flies 



Function Polymorphism :

                 Python functions can accept any data type.

Python
def add(a, b): return a + b print(add(10, 5)) print(add("Py", "thon"))