DEV Community

Cover image for Polymorphism in Python
Sona
Sona

Posted on

Polymorphism in Python

Imagine you have a program with classes representing a Car, a Boat, and a Plane. Each class has a method called move(). Even though they share the same method name, when you call move() on a Car object, it drives; on a Boat object, it sails; and on a Plane object, it flies. This ability for different objects to respond to the same method name in their own way is what we call polymorphism in Python.

In simple terms, polymorphism allows you to use a common interface (method name) across different classes, and each class can implement that interface in its own specialized manner. It makes your code more flexible and versatile, allowing you to work with diverse objects in a unified way.

Lets take an Example of a Python function that can be used on different objects - len() function.

x = "Hello World!"

print(len(x))

in the above code len() function will return number of characters.

Similarly if we take a example of tuple then len() function will be used to return the number of items in the tuple check below the code

mytuple = ("apple", "banana", "cherry")

print(len(mytuple))

Polymorphism is commonly applied in class methods, enabling the existence of multiple classes sharing the same method name.

read more below

Polymorphism in Python, Method in Python, Python Polymorphism

Polymorphism in Python - How to Become Master in Method & Class, Python Polymorphism, Python tutorial.

favicon codemagnet.in

Top comments (0)