Polymorphism literally means one which is having many forms. When it comes to Python for Data Science, it means using the same function name for different types.

python data science

The above example shows an in-built polymorphic function. Further, we will look at an example of user defined function.

python data science

Polymorphism using Class Method:

The code below shows how we can use two different class types in the same way. In the example below, we create a for loop that iterates through a tuple of objects. After that, those methods are called without being concerned about which class type each object is. It is assumed as these methods actually exist in each class.

Polymorphism with Inheritance:

Polymorphism helps us to define methods in the child class, which has the same name as the methods in the parent class. In the case of inheritance, the child class inherits the methods from the parent class. We can also modify the method in a child class, which is inherited from the parent class. This comes in handy in case where the inherited method does not fit the child class. In this case, we have to re-implement the child class. This re-implementing method is known as Method Overriding.

Polymorphism using function and objects:

We can create a function that can take any object, allowing for polymorphism. In the below example we have created a function called “func()” which takes an object which we will name as “obj”. Any instantiated object can be called into such functions. Now we will call three methods i.e., capital(), language() and type(), each of these are defined in two classes ‘India’ and ‘USA’. Below we have provided the example for further reference.

Now implementing Polymorphism with a function:

If you want to learn more about polymorphism in python for data science, then you can check this and this as well.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.