πŸ“¦ Polymorphism in Python

πŸ”Ή Definition

Polymorphism in Python means β€œone name, many forms.” In simple words, polymorphism allows the same function or method name to behave differently depending on the object that is calling it.

It helps programs become more flexible and easier to extend. Instead of writing separate code for each situation, polymorphism lets us use a single interface that works in different ways.

In real life, the same action can produce different results. For example, the word β€œrun” has different meanings when used for a person, a machine, or a computer program. Python follows the same idea in programming.

Article Algo

πŸ“Œ Basic Syntax Idea

Polymorphism usually appears through:

  • Method overriding
  • Function polymorphism
  • Operator overloading
  • Duck typing

There is no special keyword for polymorphism in Python.

πŸ“‚ Examples of Polymorphism in Python

1️⃣ Polymorphism using Method Overriding

Example
class Animal:
  def speak(self):
    print("Animal makes a sound")

class Dog(Animal):
  def speak(self):
    print("Dog barks")

class Cat(Animal):
  def speak(self):
    print("Cat meows")

a1 = Dog()
a2 = Cat()

a1.speak()
a2.speak()
Explanation

Here, the method speak() has the same name but behaves differently for Dog and Cat. This is polymorphism through method overriding.

2️⃣ Polymorphism using a Function

Example
def add(a, b, c=0):
  return a + b + c

print(add(2, 3))
print(add(2, 3, 4))
Explanation

The same function add() works with different numbers of arguments. This shows function polymorphism.

3️⃣ Polymorphism using Different Classes (Duck Typing)

Example
class Car:
  def move(self):
    print("Car drives on road")

class Boat:
  def move(self):
    print("Boat moves in water")

for vehicle in (Car(), Boat()):
  vehicle.move()
Explanation

Different objects respond differently to the same method call. Python only checks whether the method exists, not the object type. This is known as duck typing.

πŸ”‘ Key Points to Remember

  • Same method name can behave differently
  • Improves flexibility and reusability
  • Achieved without special keywords
  • Supports clean and extensible code

πŸ“Œ Conclusion

Polymorphism makes Python programs flexible, reusable, and clean. It allows one interface to work with different data types or objects, reducing complexity and improving readability. It is a key pillar of object-oriented programming.