What is 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
Types of Polymorphism in Python
Python mainly supports runtime polymorphism (method overriding) and compile-time-like polymorphism (method overloading via default arguments or *args).
1. Polymorphism with Functions and Objects
A single function can work with different types of objects.
# Example: Same function name, different object typesclass Dog: def speak(self): return "Woof!"class Cat: def speak(self): return "Meow!"def animal_sound(animal): print(animal.speak())# Using polymorphismdog = 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.
2. Polymorphism with Inheritance (Method Overriding)
Child classes can override methods from the parent class.
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 polymorphismfor bird in [Sparrow(), Penguin()]: print(bird.fly())
Output:
Sparrow flies high.Penguins can't fly.
3. Polymorphism with Built-in Functions
Many built-in functions in Python are polymorphic.
print(len("Hello")) # Works on string → 5print(len([1, 2, 3])) # Works on list → 3
4. Operator Overloading (Special Methods)
Operators like +, *, etc., behave differently for different data types.
print(5 + 10) # Integer addition → 15print("Hi " + "Py") # String concatenation → Hi Py
You can define custom behavior using magic methods:
class Book: def __init__(self, pages): self.pages = pages def __add__(self, other): return self.pages + other.pagesb1 = 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).
Key Takeaways
- Polymorphism lets the same interface work for different data types or classes.
- In Python, it’s often achieved through method overriding, duck 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?
