POLYMORPHISM IN PYTHON

Python Free Tutorial

Polymorphism refers to certain items appearing in different forms or ways. Polymorphism in python provides the ability for classes to provide different implementations of methods that are called through the same name. Overloading is a kind of polymorphism. It allows a single name or operator to be associated with different operations, depending on the type of data it has passed. 

Polymorphism is one of the main features of OOP as it extends the handling of data types and operations. To make use of polymorphism, we’re going to create two distinct classes (Football() and Cricket() ) to use with two distinct objects. Each of these distinct classes needs to have an interface that is in common( play() ) so that they can be used polymorphically, so we will give them methods that are distinct but that have the same name.

>>> class Football():
         def play(self):
              print("Football is played with legs")
>>> class Cricket():
         def play(self):
              print("Cricket is played with the hand")

Let’s instantiate these classes into two objects:

>>> Ronaldo = Football()
>>> Sachin = Cricket()

To show polymorphism in python, we are creating a for loop that iterates through a tuple of objects. Here, we are calling the methods without being concerned about which class type each object is.

>>> for game in (Ronaldo, Cricket):
>>> game.play()
 
Output:
Football is played with legs
          Cricket is played with the hand

This shows that Python is using these methods in a way without knowing or caring exactly what class type each of these objects is. That is, using these methods in a polymorphic way.

This page is contributed by Diwas. If you like AIHUB and would like to contribute, you can also write an article & mail your article to  [email protected] . See your articles appearing on AI HUB platform and help other AI Enthusiast.

About Diwas Pandey

Highly motivated, strong drive with excellent interpersonal, communication, and team-building skills. Motivated to learn, grow and excel in Data Science, Artificial Intelligence, SEO & Digital Marketing

View all posts by Diwas Pandey →

2 Comments on “POLYMORPHISM IN PYTHON”

  1. Great post. I was checking constantly this blog and I am impressed!
    Very helpful info specifically the last part :
    ) I care for such info much. I was looking for this particular info for a very long time.
    Thank you and good luck. adreamoftrains web hosting providers

Leave a Reply

Your email address will not be published. Required fields are marked *