Polymorphism Python

Python tutorial · PySpark.in

What is Polymorphism?

Polymorphism means “many forms.” In Python OOP, it allows the same function or method name to behave differently based on the object or data type it is acting upon.

Real-Life Example

Think about the word “run”:

Even though the action “run” is the same word, it behaves differently based on who or what is performing it. That’s Polymorphism.

Example 1: Built-in Polymorphism

Python supports polymorphism even with built-in functions.

PYTHON
1print(len("Megha")) # String
2print(len([10, 20, 30])) # List
3print(len({"a": 1, "b": 2})) # Dictionary
▶ Output will appear here.

The same len() function works differently for strings, lists, and dictionaries.

Example 2: Polymorphism with Classes and Methods

polymorphism works with user-defined classes.

A subclass can override a method from its parent class.

PYTHON
1class Bird:
2 def intro(self):
3 print("There are many types of birds.")
4 def flight(self):
5 print("Most birds can fly.")
6class Penguin(Bird):
7 def flight(self):
8 print("Penguins cannot fly, they swim.")
9# Objects
10bird1 = Bird()
11bird2 = Penguin()
12bird1.intro()
13bird1.flight()
14bird2.intro()
15bird2.flight()
▶ Output will appear here.

Here, the same method flight() behaves differently for different objects (Bird and Penguin).

Example 3: Polymorphism Using a Common Interface

Different objects can be passed to the same function, and the function will call their respective methods.

PYTHON
1class Dog:
2 def sound(self):
3 return "Bark"
4class Cat:
5 def sound(self):
6 return "Meow"
7# Function showing polymorphism
8def animal_sound(animal):
9 print(animal.sound())
10dog = Dog()
11cat = Cat()
12animal_sound(dog)
13animal_sound(cat)
▶ Output will appear here.

Same function animal_sound()
Works for both Dog and Cat
That’s polymorphism through duck typing

Example 4: Polymorphism with Inheritance and super()

PYTHON
1class Shape:
2 def area(self):
3 print("This method should be overridden by subclasses.")
4class Circle(Shape):
5 def area(self):
6 print("Area = π × r²")
7class Rectangle(Shape):
8 def area(self):
9 print("Area = length × width")
10# Loop through different objects
11for shape in [Circle(), Rectangle()]:
12 shape.area()
▶ Output will appear here.

Both Circle and Rectangle override the same method area() — this is method overriding, a type of polymorphism.

Both classes provide their own version of area()
This is method overriding → a key form of polymorphism

Why Polymorphism Is Important?

More Python tutorials

All tutorials · Try the free PySpark compiler · Practice challenges