Python Polymorphism

Python Polymorphism

Kishore V


Python Polymorphism

The term polymorphism comes from Greek words meaning “many forms.”

In programming, polymorphism allows the same function or method name to behave differently depending on the object or data type it is used with.

This makes code flexible, reusable, and easier to extend.

Function Polymorphism

In Python, many built-in functions work with different data types.

The behavior changes automatically based on the object passed.

Example: len() Function

Using len() with a String
Returns the total number of characters.

Output:

12
Try it Yourself

Using len() with a List
Returns the number of elements in the list.

Output:

4
Try it Yourself

Using len() with a Dictionary
Returns the number of key–value pairs.

Output:

3
Try it Yourself

Even though the function name is the same, it behaves differently for each data type. This is function polymorphism.

Polymorphism with Classes

Polymorphism is commonly used in object-oriented programming when multiple classes share the same method name but implement it in different ways.

Example

Different classes responding differently to the same method call:

Output:

Dog barks
Cat meows
Bird chirps
Try it Yourself

Each object responds to speak() in its own way, even though the method name is identical.

Polymorphism Using Inheritance

Polymorphism also works with parent and child classes.

Child classes can inherit methods from a parent class and override them if needed.

Example

Create a base class and multiple child classes:

Output:

LG Washer
Washing clothes
Samsung Fridge
Cooling food
IFB Microwave
Appliance is operating
Try it Yourself

Our website uses cookies to enhance your experience. Learn More
Accept !