×

Method Overloading in Python

Overloading is a capability of a method and operator to behave differently according to the nature of parameters.

Overloading is popular because it provides a good number of advantages:

  • Reusability of code.
  • Reduces the time required in writing the same code repeatedly.
  • Debugging becomes easier.
  • Decreases complication and raises clarity of code.

Python supports two types of overloading: -

  1. Operator overloading
  2. Function or Method Overloading

Operator Overloading

Use of arithmetic operators to provide special meaning to the operators. E.g.- ‘+’ can be used to add string and float besides int.

Other arithmetic operators like -, *, /, % can also be overloaded.

Method Overloading

Whenmore than one methodor functionhas an identicalname, but a dissimilar parameter list which results in varying method signatures, is termed method overloading.

Two or more no. of methods which are also called functions, can participate in method overloading based on the succeeding three criteria:

  1. Quantity of arguments
  2. Forms of arguments
  3. Order of arguments.

The basic syntax of a function:

Method1(int a) {
}
Method2(int a, int b){
}


Method Overloading is provided by most object-oriented programming languages such as C++, Java.

Python does not support method overloading by default, but it can be achieved in two ways which we will see in the upcoming part. 

Method Overloading in Python

The issue with method overloading in Python

Multiple methods can also be overloaded here but only the newest defined method can be used making, other methods vague.

Here’s an example to understand the issue better.

#  sum method 1 accepts two arguments and gives out their sum
def sum (a1, a2 ):
	sm = a1 + a2
	print(sm)


# sum method 2 accepts two arguments and gives out their sum


def sum (a1, a2, a3, a4):
	sm = a1 + a2 + a3 + a4
	print(sm)	
# sum method 3 accepts three arguments and gives out their sum
def sum (a1, a2, a3):
	sm = a1 + a2 + a3
	print(sm)


#  line below shows an error if it is not commented	
# sum (7, 8)
# sum (44, 21, 6, 9)


# This line will call the third sum method
sum (8, 7, 9)


OUTPUT:

Method Overloading in Python

Explanation: Here, we can see the starting two-sum method has not been used. Only the newest one is in action. So, this would not fulfill our purpose.

We have got two ways to resolve this issue. Here we begin to see both of them one by one.

METHOD 1


# Function to input multiple arguments
def sum(data_type, *args):


	# if datatype is int
	# initialize answer as 0
	if data_type =='int':
		result = 0
		
	# if datatype is str
	# initialize answer as ''
	if data_type =='str':
		result =''


	# Traversing through the arguments
	for i in args:


		# This will perform addition if the
		# arguments are int. Or concatenation
		# if the arguments are str
		result = result + i


	print(result)


# Integer data
sum('int', 45, 86)
sum('int', 78, 87)


# String data
sum('str', 'Hello ', 'developers')
sum('str', 'Hello ' , 'aspirants')

OUTPUT:

Method Overloading in Python

Explanation: This method solves the issue, but the usage of if…else statements increase the no. of lines of code which makes the code complex. Thus, it is not an effective way of method overloading.

METHOD 2

Using the Multiple Dispatch Decorator tool, which is of great utility in python.

Prerequisite:

The multiple dispatch Decorator tool has to be installed.

pip3 install multiple dispatch

Let’s understand through an example-

from multipledispatch import dispatch


#passing one parameter
@dispatch(int, int)
def addition(first, second):
	sum = first + second
	print(sum);


#passing two parameters
@dispatch(int, int, int)
def addition(first, second, third):
	sum = first + second + third
	print(sum);


#passing values of float datatypes
@dispatch(float, float, float)
def addition(first, second, third):
	sum = first + second + third
	print(sum);


#passing values of float and int datatypes
@dispatch(float, int, int, float)
def addition(first, second, third):
	sum = first + second + third
	print(sum);


#calling addition method with 3 arguments of int datatype
addition(7,8,9)
 #this will give an output of 24


#calling addition method with 3 arguments of float datatype
addition(4.8,2.2,3.0)
 # this will give output of 10.0


#calling addition method with 4 arguments of float and int datatype
addition(5.0, 3, 6, 5.0)
# this will give an output of 19.0


Although, Python doesn’t provide a default method of overloading, it can be altered to use method overloading by using the Multiple dispatch decorator tool.


Related Topics

Explain sklearn clustering in Python

Make a connection and patterns across datasets by using clustering, one of the unsupervised machine learning approaches. Grouping is crucial because it ensures unlabelled data's natural clustering. The sample from...

7 minutes read.

Python program to count and display vowels in a string

Python program to count and display vowels in a string This python program counts the vowels in a string and displays them on the screen. We can do this in several...

2 minutes read.

Python Logging Maxbytes

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

6 minutes read.

How to Convert Int to String in Python?

Every value we use or store in a variable in Python will have a specific data type. It describes the value's nature; based on that, Python will automatically assign a...

4 minutes read.

Convert String to Binary in Python

String to binary The strings can be defined as the array of Unicode code characters. Binary Binary is defined as the number system which consists two symbols 0 and 101. It is base-2...

2 minutes read.

Python datetime

Python provides a module named datetime to work with the date and time. Sometimes in the real life application development, we need to work with the date and time. The date is...

3 minutes read.

Python Percentage Sign

In Python, the percentage sign significantly completes two things. They are: It goes about as a Modulo administrator. It helps in string organizing. Allow us to see every one of them plainly. Modulo operator: Like...

2 minutes read.

Python if statement

Python if statement Decision making is an essential feature of any programming languages. Condition checking is the strength of decision making. Python provides many decision-making statements, such as: If statementIf-else statementelif statement if statement The if statement is...

2 minutes read.

How to Fix an EOF Error in Python?

Introduction An EOF (End-of-File) error occurs when a program tries to read beyond the end of a file or a stream, causing it to return an error message. It can happen...

8 minutes read.

How to Concatenate Two Strings in Python

How to Concatenate Two Strings in Python Like the other data types, operations on strings are quite useful when we deal with some real-life applications. Here we will talk about a simple...

4 minutes read.

Python BytesIO

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

How to Install Matplotlib in Python?

How to Install Matplotlib in Python The speed at which the enormous amount of data is generating has become a huge aid in understanding what's going on currently in the market....

4 minutes read.

Python Argmin

Introduction The argmin function is defined as numpy.argmin(). This function returns the index of the minimum value or element from a Numpy array in a specific axis. An array is taken...

3 minutes read.

Python vs Java

There are a lot of programming languages out there, and every day, a new programming language is developing in some parts of the world. Each programming language is a mixture...

5 minutes read.

Python TCP Server

The TCP server library is also known as the socket library. Socket programming is the method of connecting two nodes through a network to form communication between two nodes. In...

3 minutes read.

GUI to Shut down, Restart and Logout from the PC using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

4 minutes read.

Notepad++ For Python

In this article, you are going to learn what notepad++ is and how it is integrated with python to use the python programming language. You can also learn how to...

4 minutes read.

How to Define a Function in Python?

What is a Function? In programming, a piece of code that executes a specific task or a group of related operations is known as a function. What does Python Functions Do? If you...

6 minutes read.

Python lambda() Function

In this tutorial, we will learn about a new concept known as the Lambda function. It is a relatively new concept while learning Python. Python lambda functions are anonymous functions. It...

3 minutes read.

Python String center() method

Python String center() method The center() method will center align the string, using a specified character (space is default) as the fill character. Syntax string.center(width[, fillchar]) Parameter width This parameter represents the length of the returned string. fillchar...

1 minute read.