Python Polymorphism
Table of Contents
In the last lesson, we learned about Python Inheritance. After learning about inheritance, let us learn about polymorphism in Python. Polymorphism means βmany forms.β It lets us use the same method name for different types.
In this tutorial, we will learn what polymorphism is, how to use it, and why it is useful.
What Is Polymorphism in Python?
Polymorphism is the ability of different objects to respond to the same method call in different ways.
Think of it like this. When we press the βplayβ button on different devices, they all play. But a phone plays music, a TV plays video, a game console plays a game. Same action, different behavior.
In Python, polymorphism lets us write code that works with different types of objects. As long as they have the same method, it works.
Why Do We Need Polymorphism in Python?
Polymorphism makes our code flexible. We can write a function that works with many types of objects. We do not need to know the exact type. We just need to know what methods it has.
That makes our code easier to extend. We can add new types without changing the existing code.
How to Use Polymorphism in Python
Polymorphism works naturally with inheritance. If different classes have the same method, we can call that method on any of them.
class Dog: def speak(self): print("Woof!")
class Cat: def speak(self): print("Meow!")
class Cow: def speak(self): print("Moo!")
animals = [Dog(), Cat(), Cow()]
for animal in animals: animal.speak()Output
Woof!Meow!Moo!Each animal has a speak method. We loop through the list and call speak on each one. They all respond in their own way. That is polymorphism.
Polymorphism with Functions in Python
We can write a function that takes any object with a speak method.
def make_sound(animal): animal.speak()
make_sound(Dog())make_sound(Cat())make_sound(Cow())Output
Woof!Meow!Moo!The function does not care what type the object is. It just calls the speak method. That is the power of polymorphism.
Polymorphism with Inheritance in Python
Polymorphism is often used with inheritance. The parent class defines a method. The child classes override it.
class Shape: def area(self): pass
class Circle(Shape): def __init__(self, radius): self.radius = radius
def area(self): return 3.14 * self.radius ** 2
class Rectangle(Shape): def __init__(self, width, height): self.width = width self.height = height
def area(self): return self.width * self.height
shapes = [Circle(5), Rectangle(4, 6)]
for shape in shapes: print(shape.area())Output
78.524Each shape has its own area method. But we can call it the same way. That is polymorphism.
Method Overloading in Python
Some languages let us define multiple methods with the same name but different parameters. Python does not support this directly.
But we can use default arguments or variable arguments to achieve something similar.
class Calculator: def add(self, a, b=0, c=0): return a + b + c
calc = Calculator()print(calc.add(5))print(calc.add(5, 10))print(calc.add(5, 10, 15))Output
51530That works like method overloading.
Method Overriding in Python
Method overriding is when a child class provides its own version of a method from the parent class.
class Animal: def speak(self): print("Some sound")
class Dog(Animal): def speak(self): print("Woof!")
animal = Animal()dog = Dog()
animal.speak()dog.speak()Output
Some soundWoof!That is method overriding. It is a form of polymorphism.
A Real-Life Example β Payment Methods
class Payment: def pay(self, amount): pass
class CreditCard(Payment): def pay(self, amount): print(f"Paid {amount} using credit card")
class PayPal(Payment): def pay(self, amount): print(f"Paid {amount} using PayPal")
class Cash(Payment): def pay(self, amount): print(f"Paid {amount} using cash")
payments = [CreditCard(), PayPal(), Cash()]
for payment in payments: payment.pay(100)Output
Paid 100 using credit cardPaid 100 using PayPalPaid 100 using cashThat is polymorphism in action. Same method name, different behavior.
Common Mistakes with Polymorphism in Python
Mistake 1: Forgetting to define the method in the child class
class Animal: def speak(self): pass
class Dog(Animal): pass
dog = Dog()dog.speak() # Does nothingFix: Override the method in the child class.
class Dog(Animal): def speak(self): print("Woof!")Mistake 2: Using the wrong method name
class Dog: def bark(self): print("Woof!")
class Cat: def meow(self): print("Meow!")
animals = [Dog(), Cat()]
for animal in animals: animal.speak() # Error!Fix: Use the same method name for all.
class Dog: def speak(self): print("Woof!")
class Cat: def speak(self): print("Meow!")Mistake 3: Thinking polymorphism only works with inheritance
Polymorphism works with any objects that share a method name. Inheritance is not required.
Next, we will learn about Python Encapsulation and protect and control access to object data.