Polymorphism in Python
Polymorphism is the third major pillar of OOP.
1. What is Polymorphism?
The word Polymorphism comes from:
- Poly → Many
- Morphism → Forms
So, polymorphism means one interface or method can have multiple forms or behaviors.
Simple definition
Polymorphism allows the same method, function, or operator to behave differently depending on the object or data being used.
2. Simple Example
Suppose different animals have a sound() method.
class Dog: def sound(self): print("Bark") class Cat: def sound(self): print("Meow")
Both classes have:
sound()
But they behave differently.
dog = Dog() cat = Cat() dog.sound() cat.sound()
Output:
Bark Meow
The method name is the same:
sound()
but the behavior is different.
That is polymorphism.
3. Types of Polymorphism in Python
Polymorphism in Python can be understood through:
- Method Overriding
- Duck Typing
- Operator Overloading
- Function Polymorphism
- Method Overloading-like behavior
4. Method Overriding
Method overriding occurs when a child class provides its own implementation of a method that already exists in the parent class.
Example
class Animal: def sound(self): print("Animal makes a sound") class Dog(Animal): def sound(self): print("Dog barks") class Cat(Animal): def sound(self): print("Cat meows")
Now:
animals = [Dog(), Cat()] for animal in animals: animal.sound()
Output:
Dog barks Cat meows
The same:
animal.sound()
produces different behavior.
5. Polymorphism with a Common Function
We can create one function that works with different objects.
class Dog: def sound(self): print("Bark") class Cat: def sound(self): print("Meow") def make_sound(animal): animal.sound() make_sound(Dog()) make_sound(Cat())
Output:
Bark Meow
The function doesn't need to know whether it received a Dog or Cat.
It only needs the object to provide:
sound()
6. Duck Typing
Duck typing is an important Python approach to polymorphism.
The idea is:
If an object behaves like the required type, Python can use it.
A common informal explanation is:
"If it walks like a duck and quacks like a duck, treat it like a duck."
Example:
class Dog: def speak(self): print("Bark") class Cat: def speak(self): print("Meow") class Person: def speak(self): print("Hello")
Now:
def speak(obj): obj.speak() speak(Dog()) speak(Cat()) speak(Person())
Output:
Bark Meow Hello
The function doesn't care about the class.
It only cares that the object has:
speak()
7. Operator Overloading
Python operators can behave differently depending on the data.
For example:
print(10 + 20)
Output:
30
But:
print("Hello " + "World")
Output:
Hello World
The same + operator has different behavior.
It performs:
Numbers → Addition Strings → Concatenation
This is a form of polymorphic behavior.
8. Operator Overloading with Classes
We can define how operators work with our own objects.
Python uses special methods for this.
For example:
__add__()
controls the + operator.
Example
class Number: def __init__(self, value): self.value = value def __add__(self, other): return self.value + other.value a = Number(10) b = Number(20) print(a + b)
Output:
30
Here:
a + b
internally uses:
__add__()
9. Common Operator Methods
| Operator | Special Method |
|---|---|
+ | __add__() |
- | __sub__() |
* | __mul__() |
/ | __truediv__() |
// | __floordiv__() |
% | __mod__() |
** | __pow__() |
== | __eq__() |
!= | __ne__() |
< | __lt__() |
> | __gt__() |
<= | __le__() |
>= | __ge__() |
10. Function Polymorphism
Python's built-in functions can work with different types of objects.
For example:
print(len("Python"))
Output:
6
And:
print(len([10, 20, 30]))
Output:
3
And:
print(len((10, 20, 30, 40)))
Output:
4
The same function:
len()
works with different types.
This is polymorphic behavior.
11. Method Overloading
In languages such as C++, you can create multiple methods with the same name but different parameters.
For example:
add(int, int) add(int, int, int)
Python does not support traditional method overloading in the same way.
If you define the same method twice:
class Calculator: def add(self, a, b): return a + b def add(self, a, b, c): return a + b + c
The second add() replaces the first one.
12. Achieving Overloading-like Behavior
Python commonly uses default arguments.
class Calculator: def add(self, a, b=0, c=0): return a + b + c
Now:
calculator = Calculator() print(calculator.add(10)) print(calculator.add(10, 20)) print(calculator.add(10, 20, 30))
Output:
10 30 60
One method can handle different numbers of arguments.
13. *args for Flexible Arguments
Another approach is *args.
class Calculator: def add(self, *numbers): return sum(numbers)
Now:
calculator = Calculator() print(calculator.add(10, 20)) print(calculator.add(10, 20, 30)) print(calculator.add(1, 2, 3, 4, 5))
Output:
30 60 15
14. Polymorphism with Inheritance
Polymorphism is commonly used together with inheritance.
Animal / \ Dog Cat | | sound() sound() ↓ ↓ Bark Meow
Parent:
class Animal: def sound(self): pass
Children:
class Dog(Animal): def sound(self): print("Bark") class Cat(Animal): def sound(self): print("Meow")
The same method:
sound()
has different implementations.
15. Polymorphism vs Method Overriding
These are related but not exactly the same.
Method Overriding
A child class changes a method inherited from the parent.
Polymorphism
The same interface/method can be used with different objects and produce different behavior.
So:
Method overriding is one common way to achieve polymorphic behavior.
16. Polymorphism vs Inheritance
| Inheritance | Polymorphism |
|---|---|
| Reuses parent class features | Provides different behaviors |
| Creates parent-child relationship | Allows common interface |
| Focuses on code reuse | Focuses on flexibility |
Example: Dog(Animal) | Example: Dog.sound() and Cat.sound() |
They are often used together, but they are different concepts.
17. Advantages of Polymorphism
1. Flexibility
The same code can work with different objects.
2. Code Reusability
A common function can handle different object types.
3. Easy Extension
New classes can often be added without changing existing code.
4. Cleaner Code
You can work with a common interface instead of checking every class manually.
5. Supports OOP Design
Polymorphism makes inheritance and abstraction more powerful.
18. Important Concepts
Polymorphism | +----------------+----------------+ | | | Method Overriding Duck Typing Operator Overloading | +----------------+ | Method Overloading-like behavior
Remember
Polymorphism = One interface, many behaviors.
The most important things to learn are:
- Method overriding
- Duck typing
- Operator overloading
- Function polymorphism
- Python's approach to method overloading