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
- Method Overriding
- Method Overloading
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 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 Python functions can accept any data type.
def add(a, b): return a + b print(add(10, 5)) print(add("Py", "thon"))