Categories
Computer Science

Object Oriented Programming – Polymorphism 

Polymorphism means “many forms”.
In OOP, it allows the same method name (or operator) to behave differently depending on the object or data type it is acting upon.

It helps in:

  • Code reusability
  • Flexibility
  • Maintainability

Python mainly supports runtime polymorphism (method overriding) and compile-time-like polymorphism (method overloading via default arguments or *args).

A single function can work with different types of objects.

Python
# Example: Same function name, different object types
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
def animal_sound(animal):
print(animal.speak())
# Using polymorphism
dog = Dog()
cat = Cat()
animal_sound(dog) # Woof!
animal_sound(cat) # Meow!

Here, animal_sound() works with any object that has a .speak() method — this is duck typing in Python.

Child classes can override methods from the parent class.

Python
class Bird:
def fly(self):
return "Some birds can fly."
class Sparrow(Bird):
def fly(self):
return "Sparrow flies high."
class Penguin(Bird):
def fly(self):
return "Penguins can't fly."
# Runtime polymorphism
for bird in [Sparrow(), Penguin()]:
print(bird.fly())

Output:

Sparrow flies high.
Penguins can't fly.

Many built-in functions in Python are polymorphic.

Python
print(len("Hello")) # Works on string → 5
print(len([1, 2, 3])) # Works on list → 3

Operators like +*, etc., behave differently for different data types.

print(5 + 10) # Integer addition → 15
print("Hi " + "Py") # String concatenation → Hi Py

You can define custom behavior using magic methods:

Python
class Book:
def __init__(self, pages):
self.pages = pages
def __add__(self, other):
return self.pages + other.pages
b1 = Book(100)
b2 = Book(200)
print(b1 + b2) # 300

Sure! Let’s break down polymorphism in Python in the context of Object-Oriented Programming (OOP).

  • Polymorphism lets the same interface work for different data types or classes.
  • In Python, it’s often achieved through method overridingduck typing, and operator overloading.
  • It improves code flexibility and reduces duplication.

If you want, I can prepare a single Python program that demonstrates all types of polymorphism in one place for easy learning.
Do you want me to create that?