- Learning Objectives
- Prerequisites
- Introduction
- What is Polymorphism?
- Why is Polymorphism Required?
- Real-World Examples
- Types of Polymorphism
- Compile-Time Polymorphism
- Run-Time Polymorphism
- Method Overriding
- Duck Typing
- Operator Overloading
- Method Overloading in Python
- Internal Working
- Summary
After completing this chapter, you will be able to:
- Understand Polymorphism.
- Explain why Polymorphism is required.
- Differentiate Compile-Time and Run-Time Polymorphism.
- Understand Method Overriding.
- Learn Duck Typing.
- Understand Operator Overloading.
- Learn how Python achieves Polymorphism.
Before learning this chapter, you should know:
- Classes
- Objects
- Inheritance
- Methods
- Constructors
Object-Oriented Programming consists of four pillars.
- Encapsulation
- Abstraction
- Inheritance
- Polymorphism
The fourth pillar is Polymorphism.
The word Polymorphism comes from two Greek words.
Poly
↓
Many
Morph
↓
Forms
Therefore,
Polymorphism means
One interface, many forms.
The same method or operation behaves differently depending on the object that uses it.
Polymorphism is the ability of an object, method, or operator to perform different actions depending on the context.
The same method name can produce different behavior for different objects.
One method behaving differently for different objects is called Polymorphism.
Suppose we have different animals.
Each animal makes a different sound.
Dog
↓
Bark
Cat
↓
Meow
Cow
↓
Moo
Instead of creating different method names
dogSound()
catSound()
cowSound()
we create one common method
sound()
Each object provides its own implementation.
This makes the code easier to maintain and extend.
Vehicle
Start()
Car
↓
Starts using Key
Bike
↓
Starts using Self Start
Electric Car
↓
Starts using Push Button
Payment
pay()
Credit Card
↓
Credit Card Payment
UPI
↓
UPI Payment
Net Banking
↓
Internet Banking Payment
The same method performs different actions.
There are two major types of Polymorphism.
Also called
- Static Binding
- Early Binding
Usually achieved through
- Method Overloading
- Operator Overloading
Also called
- Dynamic Binding
- Late Binding
Achieved through
- Method Overriding
Python mainly supports Run-Time Polymorphism.
In languages like Java and C++,
Compile-Time Polymorphism is achieved using
- Method Overloading
Python does not support true Method Overloading.
Instead,
Python achieves similar behavior using
- Default Arguments
- *args
- **kwargs
Run-Time Polymorphism occurs when the method to execute is decided while the program is running.
This is achieved using
- Inheritance
- Method Overriding
Python strongly supports Run-Time Polymorphism.
Method Overriding occurs when a Child Class provides its own implementation of a Parent Class method.
Example
class Animal:
def sound(self):
pass
class Dog(Animal):
def sound(self):
print("Dog Barks")The child class overrides the parent implementation.
Python follows the concept of Duck Typing.
Rule
"If it walks like a duck
and
quacks like a duck,
it is treated as a duck."
Python focuses on an object's behavior instead of its type.
If an object provides the required method,
Python allows it to be used.
Python allows existing operators to behave differently for user-defined objects.
Example
+Normally,
10 + 20adds integers.
Using
__add__()the same operator can work with custom objects.
Python does not support true Method Overloading.
Instead,
similar behavior is achieved using
- Default Arguments
- *args
- **kwargs
Object Created
↓
Method Called
↓
Python Finds Object Type
↓
Corresponding Method Executes
↓
Output Produced
- Improves flexibility.
- Reduces duplicate code.
- Supports code reusability.
- Easy maintenance.
- Easy extension.
- Cleaner program design.
Polymorphism is used in
- Banking Systems
- Payment Gateways
- GUI Frameworks
- Game Development
- Machine Learning Libraries
- Web Frameworks
- Database Drivers
In this part, we learned:
- Polymorphism
- Need for Polymorphism
- Types of Polymorphism
- Compile-Time Polymorphism
- Run-Time Polymorphism
- Method Overriding
- Duck Typing
- Operator Overloading
- Internal Working
Write a Python program to demonstrate Method Overriding.
class Animal:
def sound(self):
print("Animals make different sounds")
class Dog(Animal):
def sound(self):
print("Dog Barks")
dog = Dog()
dog.sound()Dog Barks
Animalis the Parent Class.Dogis the Child Class.- The
sound()method in the child class overrides the parent'ssound()method. - Since the object belongs to
Dog, the child method executes.
Write a Python program to call both Parent and Child methods.
class Animal:
def sound(self):
print("Animals make sounds")
class Dog(Animal):
def sound(self):
super().sound()
print("Dog Barks")
dog = Dog()
dog.sound()Animals make sounds
Dog Barks
super() calls the parent class method first.
After the parent method completes,
the child method executes.
Write a Python program to demonstrate Runtime Polymorphism.
class Bird:
def fly(self):
print("Bird Flies")
class Eagle(Bird):
def fly(self):
print("Eagle Flies High")
class Sparrow(Bird):
def fly(self):
print("Sparrow Flies Low")
birds = [Eagle(), Sparrow()]
for bird in birds:
bird.fly()Eagle Flies High
Sparrow Flies Low
The same method
fly()behaves differently for different objects.
Python decides which method to execute at runtime.
Write a Python program to demonstrate Duck Typing.
class Duck:
def speak(self):
print("Quack Quack")
class Human:
def speak(self):
print("Hello")
def call_speak(obj):
obj.speak()
duck = Duck()
human = Human()
call_speak(duck)
call_speak(human)Quack Quack
Hello
The function
call_speak()does not check the object's type.
It simply calls
speak()If the object has a speak() method,
Python executes it.
This is Duck Typing.
Write a Python program to overload the + operator.
class Number:
def __init__(self, value):
self.value = value
def __add__(self, other):
return Number(self.value + other.value)
num1 = Number(10)
num2 = Number(20)
result = num1 + num2
print(result.value)30
Python converts
num1 + num2into
num1.__add__(num2)This is called Operator Overloading.
class Car:
def start(self):
print("Car Started")
class Bike:
def start(self):
print("Bike Started")
def vehicle_start(vehicle):
vehicle.start()
vehicle_start(Car())
vehicle_start(Bike())Car Started
Bike Started
Neither Car nor Bike inherits from a common parent.
However,
both provide the
start()method.
Python allows this because it focuses on an object's behavior rather than its type.
Create Object
↓
Call Method
↓
Python Identifies Object
↓
Corresponding Method Executes
↓
Output Displayed
Animal
▲
│
Dog
│
Dog Object
↓
sound()
↓
Dog Barks
- Improves code flexibility.
- Promotes code reuse.
- Makes programs easier to extend.
- Reduces duplicate code.
- Supports dynamic behavior.
- Improves maintainability.
- Use Method Overriding when child classes require different behavior.
- Prefer polymorphism over multiple conditional statements.
- Use meaningful method names.
- Use Duck Typing only when objects share common behavior.
- Avoid unnecessary inheritance.
Changing the method name instead of overriding.
❌ Incorrect
class Dog(Animal):
def bark(self):
passThis is not Method Overriding.
Forgetting inheritance.
class Dog:Without inheritance,
Method Overriding cannot occur.
Confusing Method Overloading with Method Overriding.
| Method Overloading | Method Overriding |
|---|---|
| Same class | Parent and Child |
| Different parameters | Same parameters |
| Not directly supported | Fully supported |
Assuming Duck Typing requires inheritance.
Duck Typing depends on the presence of the required methods, not on inheritance.
Polymorphism is used in:
- Payment Gateway Systems
- Banking Applications
- GUI Frameworks
- Machine Learning Libraries
- Django Framework
- Flask Applications
- Game Development
- Data Processing Libraries
Polymorphism is the ability of the same method or operation to perform different actions for different objects.
- Compile-Time Polymorphism
- Run-Time Polymorphism
Python mainly supports Runtime Polymorphism.
Method Overriding occurs when a child class provides its own implementation of a parent class method.
Duck Typing allows objects with the required methods to be used, regardless of their class or inheritance hierarchy.
Python does not support true Method Overloading.
Similar behavior is achieved using:
- Default Arguments
*args**kwargs
Operator Overloading gives additional meaning to existing operators for user-defined objects using Magic Methods such as __add__().
Polymorphism increases flexibility, improves maintainability, reduces duplicate code, and makes applications easier to extend.
- Demonstrate Method Overriding using Animal and Dog classes.
- Create three payment classes implementing a common
pay()method. - Demonstrate Duck Typing using different objects with the same method.
- Overload the
+operator using__add__(). - Create a Vehicle hierarchy demonstrating Runtime Polymorphism.
- Polymorphism means One Interface, Many Forms.
- Python mainly supports Runtime Polymorphism.
- Method Overriding is achieved using inheritance.
- Duck Typing depends on behavior, not type.
- Operator Overloading uses Magic Methods.
- Method Overloading is simulated using default arguments,
*args, and**kwargs.
In this chapter, we learned:
- Polymorphism
- Types of Polymorphism
- Compile-Time and Run-Time Polymorphism
- Method Overriding
- Duck Typing
- Operator Overloading
- Practical Programs
- Best Practices
- Common Mistakes
- Interview Questions
- Practice Programs
- Quick Revision