A pianist can play different types of pianos, and a driver can drive different types of vehicles. This is an example of polymorphism—the ability to perform the same action in different ways.
In Python, polymorphism allows different objects to share the same method names but behave differently based on their class.
💡 Analogy: A universal remote control works with different devices—a TV, an AC, and a sound system—all with the same buttons but different behaviors.
By the end of this lesson, you will be able to:
Understand the concept of polymorphism in Object-Oriented Programming.
Use method overriding to achieve polymorphism.
Implement polymorphism with different classes having methods with the same name.
Polymorphism – The ability of different classes to implement the same method in different ways.
Method overriding – A child class redefining a method from its parent class.
Duck typing – The concept that an object's behavior is more important than its class.
Abstract classes – Classes that provide a common interface but cannot be instantiated.
Code flexibility – Writing code that can work with multiple data types or objects.
Example 1: Method Overriding for Polymorphism
class Animal:
def make_sound(self):
return "Some generic sound"
class Dog(Animal):
def make_sound(self):
return "Bark!"
class Cat(Animal):
def make_sound(self):
return "Meow!"
dog = Dog()
cat = Cat()
print(dog.make_sound()) # Output: Bark!
print(cat.make_sound()) # Output: Meow!
Not overriding methods properly—ensure method names match exactly.
Using the wrong class hierarchy, leading to unintended behavior.
🔗 Practice on W3Schools: Polymorphism – Learn how different classes can share the same method names with different behaviors.
🔗 Try It Online: Run Your Code Here – Test your Python code instantly.
1️⃣ Basic Challenge:
Create a Shape class with a draw() method that prints "Drawing a shape".
2️⃣ Extended Challenge:
Create Circle and Square classes that override draw() to print different shapes.
3️⃣ Advanced Challenge:
Write a program where multiple unrelated classes have a method describe(), demonstrating polymorphism.
Write the example from this lesson, ensuring you include:
✅ A base class with a method
✅ Child classes overriding the method
✅ Calling overridden methods from different objects
Read the example code before writing!