Introduction
Polymorphism is one of the four fundamental principles of Object-Oriented Programming (OOP). The word polymorphism means "many forms." In Python, it allows different objects to respond to the same method call in their own unique way.
For example, both a dog and a cat can have a speak() method. When that method is called, each object performs a different action. The code calling the method does not need to know what type of object it is working with.
Why Use Polymorphism?
Polymorphism makes programs more flexible by allowing different objects to be treated in the same way. It also reduces complex conditional statements and makes applications easier to extend.
- Produces cleaner code.
- Improves flexibility.
- Allows code reuse.
- Makes programs easier to extend.
- Supports scalable object-oriented design.
Basic Example
Different classes can implement methods with the same name while producing different results.
class Dog:
def speak(self):
print("Woof!")
class Cat:
def speak(self):
print("Meow!")
dog = Dog()
cat = Cat()
dog.speak()
cat.speak()
Output:
Woof!
Meow!
Polymorphism with Inheritance
Polymorphism is commonly used together with inheritance. A child class can override a method inherited from its parent class.
class Animal:
def speak(self):
print("Animal sound")
class Dog(Animal):
def speak(self):
print("Woof!")
class Cat(Animal):
def speak(self):
print("Meow!")
animals = [Dog(), Cat()]
for animal in animals:
animal.speak()
Output:
Woof!
Meow!
Duck Typing
Python supports a feature called duck typing. Instead of checking an object's type, Python only cares whether the object provides the required method. If it does, the method can be called successfully.
class Dog:
def speak(self):
print("Woof!")
class Cat:
def speak(self):
print("Meow!")
class Duck:
def speak(self):
print("Quack!")
def make_sound(animal):
animal.speak()
make_sound(Dog())
make_sound(Cat())
make_sound(Duck())
Output:
Woof!
Meow!
Quack!
Polymorphism with Functions
A single function can work with many different object types as long as they provide the methods that the function expects.
class Car:
def move(self):
print("Driving")
class Boat:
def move(self):
print("Sailing")
class Plane:
def move(self):
print("Flying")
def travel(vehicle):
vehicle.move()
travel(Car())
travel(Boat())
travel(Plane())
Output:
Driving
Sailing
Flying
Built-in Polymorphism
Many built-in Python functions are polymorphic. They work with different data types while producing appropriate results.
print(len("Python"))
print(len([1, 2, 3, 4]))
print(len({"a": 1, "b": 2}))
Output:
6
4
2
Method Overriding
Method overriding is one of the most common forms of polymorphism. A child class replaces a method inherited from its parent class with its own implementation.
class Employee:
def work(self):
print("Employee is working.")
class Manager(Employee):
def work(self):
print("Manager is supervising the team.")
employee = Employee()
manager = Manager()
employee.work()
manager.work()
Output:
Employee is working.
Manager is supervising the team.
Real-World Example
Polymorphism is widely used in real-world applications. Imagine a drawing program that supports different shapes. Every shape has a draw() method, but each one draws itself differently. The program simply calls draw() without worrying about the object's actual type.
class Circle:
def draw(self):
print("Drawing a circle.")
class Rectangle:
def draw(self):
print("Drawing a rectangle.")
class Triangle:
def draw(self):
print("Drawing a triangle.")
shapes = [Circle(), Rectangle(), Triangle()]
for shape in shapes:
shape.draw()
Output:
Drawing a circle.
Drawing a rectangle.
Drawing a triangle.
Advantages of Polymorphism
- Allows different objects to be used through a common interface.
- Reduces complex
ifandelifstatements. - Improves code readability.
- Makes applications easier to extend.
- Encourages reusable and maintainable code.
- Works naturally with inheritance and duck typing.
Best Practices
- Use meaningful method names across related classes.
- Prefer polymorphism instead of long conditional statements.
- Combine polymorphism with inheritance when appropriate.
- Keep overridden methods consistent in purpose.
- Take advantage of Python's duck typing for flexible designs.
Summary
Polymorphism allows different objects to respond to the same method call in their own unique way. Whether using inheritance, method overriding, or duck typing, polymorphism helps create Python programs that are flexible, reusable and easy to maintain. It is one of the key principles that makes Object-Oriented Programming powerful and scalable.
Examples
The following examples help reinforce the concepts explained in this lesson.
<!DOCTYPE html>
<html>
<head>
<title>My First Page</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
💡 Pro Tip
Practice every concept immediately after reading it. Learning by doing is the fastest way to master HTML.
⚠ Common Mistake
Do not simply copy code examples. Type them yourself and experiment with small changes.
Best Practices
- Write clean and readable HTML.
- Indent your code consistently.
- Use semantic HTML elements.
- Validate your HTML regularly.
- Test your pages in multiple browsers.
Frequently Asked Questions
Why should I learn HTML first?
HTML is the foundation of every website. Once you understand HTML, learning CSS and JavaScript becomes much easier.
Is HTML difficult?
No. HTML is considered one of the easiest web technologies to learn, making it an excellent starting point for beginners.