Programs

A Complete Guide To Method Overloading in Python (With examples)

Overloading is the ability of a function, method, or operator to work differently when you pass different parameters to the same. Method overloading or Function overloading in Python have commonly used terms. Some of the main advantages of overloading is that you can use one method in multiple ways, which helps you keep your code cleaner and removes complexity when working with a team.

What is Method Overloading?

In Object-Oriented Programming, Method Overloading is used in scenarios where, for a specific object, a particular method can be called in more than one way according to the project requirement.

Examples of Method Overloading in Python are discussed in detail later in the article.

 What is Method Overriding?

Method Overriding in Python is similar to Method Overloading except for that method overriding occurs between a subclass and a superclass. It has the same parameters as to when the methods are called. Yet, they behave differently due to some of the functionality being overridden from the superclass.

Example of Method Overriding

class X:

    def method1(self):

        print(‘I’m the first feature of class X’)

    def method2(self):

        print(‘I’m the second feature of class X’)

class Y(X):

    def method1(self):

        print(‘I’m the modified first feature of class X in class Y’)   

    def method3(self):

        print(‘I’m a feature of class Y’)

obj = Y()

obj.method1()

Output:

I’m the modified first feature of class X in class Y

method1 was overridden by class Y.

Learn Data Science Courses online at upGrad

Method Overloading in Python

The problem with method overloading in Python is that Python does not support it by default. However, there are workarounds to do the same.

The Problem

Let us consider the following code:

def add(a, b):

s = a + b

print(s)

def add(a, b, c):

s = a + b + c

print(s)

# add(8, 9) shows error

add(8, 9, 2)

At first glance, the code looks good, but when you try to execute it with two arguments, Python will show you an error because in Python, when you have more than one method of the same name but a different number of arguments, only the latest defined method can be used. 

There are two different ways we can overcome this problem of method overloading in Python.

1: Using the same methods differ according to the data type of the arguments

We can see an argument to know the data type, along with *args that allows passing a variable number of arguments to a method in Python. We can then use if statements to control how the method behaves according to the input.

CODE: 

def add(dt, *args):

if dt ==’int’:

s = 0

if dt ==’str’:

s = ”

for x in args:

s = s + x

print(s)

add(‘int’, 11, 9)

add(“str”, “Hello,”, “How are you?”)

Output:

20

Hello, How are you?

This was the first workaround to implement method overloading in Python.

Explore our Popular Data Science Courses

2: Using Multiple Dispatch Decorator (More efficient way)

Multiple Dispatch Decorator is less of a workaround and works exactly like it is supposed to. You can install it using pip3.

pip3 install multiple dispatches

CODE:

from multiple dispatch import dispatch

@dispatch(int,int) # for 2 integer arguments

def add(n1,n2):

    s = n1 + n2

    print(s) 

@dispatch(int,int,int) # for 3 integer arguments

def add(n1,n2,n3):

    s = n1 + n2 + n3

    print(s)

@dispatch(float,float,float) # for float arguments

def add(n1,n2,n3):

    s = n1 + n2 + n3

    print(s  

add(5,2)

add(6,1,4) 

add(3.4,1.2,5.6) 

Output:

7

11

10.2

When executing, the dispatcher makes a new object that stores different implementations of the method and decides the method to select depending on the type and number of arguments passed while calling the method. This way method of overloading in Python is more efficient.

Read our popular Data Science Articles

Conclusions

If you wish to enter the field of Data Science, Python is a good first step to take. To dive deep and study the topic further, you can check out advanced online certifications courses like the Executive Programme in Data Science by IIIT-Bangalore in association with upGrad. This program covers the important aspects of the subject and provides a lot of additional benefits like job assistance, 1:1 Mentorship, online support, live lectures, and optional additional modules for enthusiasts who want to upskill further.

What is the difference between a function and a method in Python?

In Python, there are two kinds of functions: built-in functions and user-defined functions. print() and len() are examples of built-in functions. User-defined functions in python are functions that we can define ourselves to do a specific task more than once in a typical program. Method is just like a function except that methods belong to a class and can be called only on an object. (Syntax: obj.method())

How do I choose between Python and R?

Python and R are the two top languages used for Data Science. While what to use depends on several factors like the company you’re aiming for, the type of project, client requirements, etc., generally, if you are a beginner in programming, working in an engineering environment building large-scale applications, Python is a great choice. On the other hand, if you have prior programming experience and want to run data analysis tasks rapidly and visualise your data using beautiful graphics to make a better decision statistically, R is the way to go.

How long does it take to master Data Science?

Everyone has their own learning pace. Although, for a beginner with no prior programming experience, it will take you close to 6-7 months to make your fundamentals strong. Post that, it again depends on how much you practice and the projects to work on. If you follow an online certification, you should be able to master it in around a year.

Want to share this article?

Prepare for a Career of the Future

Leave a comment

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

Our Popular Data Science Course

Get Free Consultation

Leave a comment

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

×
Let’s do it!
No, thanks.