Polymorphism is one of the important concepts of Object-Oriented Programming (OOP) in Python. The word polymorphism means "many forms", where the same method, function, or operator can behave differently depending on the object or data it is working with. Python supports polymorphism through method overriding, duck typing, operator overloading, and built-in functions that can work with different types of objects. For example, the same sound() method can produce different results for a Dog and a Cat object. Polymorphism makes programs more flexible, reusable, and easier to extend.
Table of Contents
What is Polymorphism in Python?
Polymorphism is an OOP concept that allows the same method, function, or operator to perform different operations depending on the object or data type.
The word polymorphism comes from two Greek words: "poly", meaning many, and "morph", meaning forms. Therefore, polymorphism means many forms.
For example, different classes can have a method with the same name but different implementations.
Example:
# Python program to demonstrate polymorphism
class Dog:
def sound(self):
print("Dog barks")
class Cat:
def sound(self):
print("Cat meows")
dog1 = Dog()
cat1 = Cat()
dog1.sound()
cat1.sound()
Output:
Dog barks
Cat meows
Explanation:
- The Dog class contains a sound() method.
- The Cat class also contains a sound() method.
- Both methods have the same name.
- The Dog object produces "Dog barks".
- The Cat object produces "Cat meows".
- The same method name behaves differently depending on the object.
This is an example of polymorphism.

Why Use Polymorphism in Python?
Polymorphism is useful when different objects need to perform similar operations in different ways.
- Improves Code Reusability: The same function or method can work with different objects.
- Reduces Code Duplication: Common operations can be handled using a single piece of code.
- Makes Programs Flexible: Different objects can provide their own implementation of the same method.
- Supports Extensibility: New classes can be added without significantly changing existing code.
- Supports Object-Oriented Design: Polymorphism works closely with inheritance and method overriding.
- Simplifies Code: A single function can work with objects of different classes.
- Improves Maintainability: Changes to individual class behavior can be made without changing the code that uses the objects.
How Polymorphism Works in Python?
Polymorphism allows different objects to respond to the same method call in their own way. For example, suppose different animals have a sound() method. Each animal can implement the method differently.
Example:
# Python program to demonstrate how polymorphism works
class Dog:
def sound(self):
print("Dog barks")
class Cat:
def sound(self):
print("Cat meows")
class Cow:
def sound(self):
print("Cow moos")
animals = [Dog(), Cat(), Cow()]
for animal in animals:
animal.sound()
Output:
Dog barks
Cat meows
Cow moos
Explanation:
- Three classes are created: Dog, Cat, and Cow.
- Each class defines a sound() method.
- Each sound() method has a different implementation.
- Objects of all three classes are stored in a list.
- The for loop calls sound() on each object.
- Python executes the appropriate method based on the current object.
This allows the same method call, animal.sound(), to produce different results.
Types of Polymorphism in Python
Python supports polymorphism in several ways.
The commonly used forms include:
- Method Overriding: A child class provides its own implementation of a parent class method.
- Polymorphism with Functions: The same function can work with objects of different classes.
- Polymorphism with Built-in Functions: Built-in functions such as len() can work with different types of objects.
- Duck Typing: Python focuses on whether an object supports the required behavior rather than its specific class.
- Operator Overloading: Operators such as +, -, and * can behave differently depending on the operands.
Method Overriding
Method overriding occurs when a child class provides its own implementation of a method that is already defined in the parent class. It is one of the most common ways to implement polymorphism in Python.
Example:
# Python program to demonstrate method overriding
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")
animal1 = Animal()
dog1 = Dog()
cat1 = Cat()
animal1.sound()
dog1.sound()
cat1.sound()
Output:
Animal makes a sound
Dog barks
Cat meows
Explanation:
- The Animal class defines the sound() method.
- Dog inherits from Animal and overrides sound().
- Cat also inherits from Animal and overrides sound().
- Each class provides its own implementation.
- The same sound() method call produces different outputs.
This demonstrates polymorphism through method overriding.
Polymorphism with Functions
A Python function can work with objects of different classes as long as those objects provide the required method or behavior.
Example:
# Python program to demonstrate polymorphism with functions
class Dog:
def sound(self):
print("Dog barks")
class Cat:
def sound(self):
print("Cat meows")
def make_sound(animal):
animal.sound()
dog1 = Dog()
cat1 = Cat()
make_sound(dog1)
make_sound(cat1)
Output:
Dog barks
Cat meows
Explanation:
- The Dog and Cat classes both define a sound() method.
- The make_sound() function accepts an object as an argument.
- The function calls the sound() method on that object.
- When a Dog object is passed, the Dog implementation is executed.
- When a Cat object is passed, the Cat implementation is executed.
The same function can therefore work with different types of objects.
Polymorphism with Built-in Functions
Python's built-in functions can also demonstrate polymorphism because they can work with different types of objects. For example, the len() function can be used with strings, lists, and tuples.
Example:
# Python program to demonstrate polymorphism with len()
text = "Python"
numbers = [10, 20, 30, 40]
names = ("John", "Alice", "David")
print(len(text))
print(len(numbers))
print(len(names))
Output:
6
4
3
Explanation:
- text is a string containing six characters.
- numbers is a list containing four elements.
- names is a tuple containing three elements.
- The same len() function is used for all three objects.
- The function returns the appropriate result based on the object provided.
This demonstrates how Python functions can operate on different types of objects.
Duck Typing in Python
Duck typing is an important feature of Python that supports polymorphism. The idea behind duck typing is commonly expressed as: "If it behaves like a duck, it can be treated like a duck." Instead of checking the exact type of an object, Python focuses on whether the object provides the required method or behavior.
Example:
# Python program to demonstrate duck typing
class Dog:
def sound(self):
print("Dog barks")
class Cat:
def sound(self):
print("Cat meows")
def make_sound(animal):
animal.sound()
dog1 = Dog()
cat1 = Cat()
make_sound(dog1)
make_sound(cat1)
Output:
Dog barks
Cat meows
Explanation:
- Dog and Cat are different classes.
- Both classes provide a sound() method.
- The make_sound() function does not need to check whether the object is a Dog or Cat.
- It simply calls the sound() method.
- Python uses the behavior provided by the object.
This is known as duck typing and is one of the reasons Python supports flexible object-oriented programming.
Operator Overloading
Operator overloading allows operators such as +, -, *, and == to behave differently depending on the objects being used. For example, the + operator performs numerical addition for numbers and concatenates strings.
Example:
# Python program to demonstrate operator polymorphism
print(10 + 20)
print("Hello " + "Python")
Output:
30
Hello Python
Explanation:
- The + operator is used with integers.
- With integers, it performs addition.
- The same + operator is used with strings.
- With strings, it performs concatenation.
- Therefore, the same operator behaves differently depending on the operands.
Operator overloading can also be implemented in custom classes using special methods such as __add__().
Example:
# Python program to demonstrate operator overloading with a custom class
class Number:
def __init__(self, value):
self.value = value
def __add__(self, other):
return self.value + other.value
num1 = Number(10)
num2 = Number(20)
result = num1 + num2
print(result)
Output:
30
Explanation:
- The Number class contains a value attribute.
- The __add__() method defines how the + operator works for Number objects.
- Two Number objects are created.
- The + operator calls the __add__() method.
- The values of both objects are added together.
Polymorphism with Inheritance
Polymorphism and inheritance are often used together in Object-Oriented Programming. A parent class can define a common method, while different child classes can override that method with their own implementations.
Example:
# Python program to demonstrate polymorphism with inheritance
class Shape:
def area(self):
print("Area of the shape")
class Circle(Shape):
def area(self):
print("Area of circle")
class Rectangle(Shape):
def area(self):
print("Area of rectangle")
shapes = [Circle(), Rectangle()]
for shape in shapes:
shape.area()
Output:
Area of circle
Area of rectangle
Explanation:
- The Shape class defines an area() method.
- Circle inherits from Shape and overrides area().
- Rectangle also inherits from Shape and overrides area().
- Objects of both child classes are stored in a list.
- The same shape.area() method call produces different results.
- This demonstrates polymorphism using inheritance and method overriding.
Advantages of Polymorphism
Polymorphism provides several benefits when designing Python programs.
- Code Reusability: The same function or method can work with different objects.
- Flexibility: Different classes can provide their own implementation of the same method.
- Less Code Duplication: A common function can handle multiple object types.
- Easy Extension: New classes can be added without significantly changing existing code.
- Supports Method Overriding: Child classes can customize inherited behavior.
- Improves Maintainability: Different implementations can be maintained independently.
- Supports Object-Oriented Design: Polymorphism works with inheritance and other OOP concepts.
Common Beginner Mistakes
1. Using Different Method Names: For polymorphism through a common method, the classes should provide the same method name.
Wrong:
class Dog:
def bark(self):
print("Dog barks")
class Cat:
def meow(self):
print("Cat meows")
Here, the methods have different names, so a common sound() method call cannot be used.
Correct:
class Dog:
def sound(self):
print("Dog barks")
class Cat:
def sound(self):
print("Cat meows")
Now both classes provide the same sound() method with different behavior.
2. Forgetting self in Instance Methods: Instance methods need self as their first parameter.
Wrong:
class Dog:
def sound():
print("Dog barks")
Correct:
class Dog:
def sound(self):
print("Dog barks")
3. Incorrect Method Overriding: The child class should define the method correctly when overriding a parent method.
Wrong:
class Animal:
def sound(self):
print("Animal sound")
class Dog(Animal):
def sounds(self):
print("Dog barks")
Here, sounds() is a different method name, so it does not override sound().
Correct:
class Animal:
def sound(self):
print("Animal sound")
class Dog(Animal):
def sound(self):
print("Dog barks")
4. Calling a Method That Does Not Exist: A polymorphic function should call a method that the provided objects actually support.
Wrong:
def make_sound(animal):
animal.bark()
If an object does not have a bark() method, Python will raise an AttributeError.
Correct:
def make_sound(animal):
animal.sound()
The objects passed to the function should provide the sound() method.
5. Confusing Polymorphism with Inheritance: Polymorphism does not always require inheritance. Python can achieve polymorphic behavior through duck typing and other mechanisms.
Example:
class Dog:
def sound(self):
print("Dog barks")
class Cat:
def sound(self):
print("Cat meows")
def make_sound(animal):
animal.sound()
Here, Dog and Cat do not need to inherit from the same class. They can still be used with the same function because both provide the required sound() method.
Conclusion
Polymorphism is an important Object-Oriented Programming concept in Python that allows the same method, function, or operator to behave differently depending on the object or data it works with. Python supports polymorphism through method overriding, functions, built-in functions, duck typing, operator overloading, and inheritance. Method overriding allows child classes to provide their own implementations of inherited methods, while duck typing allows Python to focus on an object's behavior instead of its exact type. Operator overloading also allows operators such as + to work differently with different types of objects. By understanding polymorphism, developers can write flexible, reusable, and maintainable Python programs.
Frequently Asked Questions (FAQs)
1. What is polymorphism in Python?
Polymorphism is an OOP concept that allows the same method, function, or operator to behave differently depending on the object or data type.
2. What does polymorphism mean?
Polymorphism means "many forms". In Python, it allows the same operation to produce different behavior for different objects or data types.
3. What are the types of polymorphism in Python?
Common forms of polymorphism in Python include method overriding, polymorphism with functions, duck typing, built-in function polymorphism, and operator overloading.
4. What is method overriding in polymorphism?
Method overriding occurs when a child class provides its own implementation of a method that is already defined in its parent class.
5. What is duck typing in Python?
Duck typing is a Python approach where the behavior or methods supported by an object are more important than its specific class or type.
0 Comments