×

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

Python program to find the GCD or HCF

Python program to find the GCD or HCF The largest positive integer that perfectly divides the two numbers is the HCF (Highest Common Factor) or GCD (Greatest Common Deviser). For example,...

5 minutes read.

Python Program for Tower of Hanoi

In this tutorial, we will examine and learn about the Python coding used to create the video game Tower of Hanoi. Before seeing the game's step-by-step implementation in Python, we...

3 minutes read.

Python IDE names

Python is one of the most renowned programming languages. It has different execution conditions and a great many compilers to execute the python programs, e.g., PyCharm, PyDev, Jupyter Notebook, Visual...

6 minutes read.

How to slice a list in python

When working with lists, we face situations where we may need a part of the list from one index to the other. Slicing is one of the simpler ways to...

5 minutes read.

Python Dictionary values() method

Python Dictionary values() method The dictionary.values() method in Python returns a view object that displays a list of all the values in the specified dictionary. Syntax dictionary.values() Parameter NA Return This method returns a view object. The...

1 minute read.

How to run a Python file in CMD

Introduction Today, let us learn about how to run a Python file using cmd. Cmd is nothing but command prompt. So first let us know how to run a Python code...

4 minutes read.

Face Recognition in Python

In this tutorial, we will understand what is face recognition and how it is achieved in python. Face recognition is of great utility in real-world scenarios. It is an extended step...

3 minutes read.

Python String encode() method

Python String encode() method The string.encode() method in Python returns an encoded version of the string. The default encoding is the current default string encoding Syntax String.encode([encoding[,errors]]) Parameter Encoding: This parameter represents a String specifying...

2 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.

What is a Script in Python

Have you ever heard that Python is a scripting language? Or when people address a Python program file as a script? Besides programming, script generally means "a written story for...

3 minutes read.

Text detection using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

How to Download Python

How to Download Python Python is the most renowned programming language and developers across the globe are working on projects that are made using Python and its libraries. Here we will...

4 minutes read.

Python History

Python is one of the top trending, widely-used programming languages. Python is a general-purpose programming language. Python language is known for its features. Some features are given below: SimplisticFree and open...

4 minutes read.

Convert List to Array in Python

What is List in Python? In Python, a list is a built-in data structure that stores a collection of items. The items in a list can be of any data type,...

3 minutes read.

Python Matrix Multiplication

One of the most fundamental mathematical structures, matrices are used often in many disciplines, including mathematics, physics, engineering, computer science, etc. For example, matrices and associated operations (multiplication and addition) are...

8 minutes read.

Python memoryview() Function

Python memoryview() Function The memoryview() function in Python returns a memory view object from a specified object. Syntax memoryview(obj) Parameter obj: This parameter represents a Bytes object or a bytearray object. Return This function returns a “memory view” object...

1 minute read.

Python sum() function

Python sum() function The sum() function in python sums start and the items of an iterable from left to right and returns the total.  Syntax sum(iterable[, start]) Parameter iterable: This parameter represents the sequence to sum. start: It is optional...

1 minute read.

Rank Based Percentile GUI Calculator using PyQt5 in Python

PyQt5: PyQt5 is one of several solutions that Python offers for creating GUI applications. Cross-platform GUI toolkit PyQt5 is a collection of Python interfaces for Qt version 5. With the capabilities...

3 minutes read.

Length of Tuple in Python

What is Tuple? Python is a data structure in a python programming language; it is the collection of the objects in a sequence. The tuples are immutable; that is, we cannot...

3 minutes read.

Python File Handling

What is the file? The file is a collection of data in a single unit. It is used to store information in the non-volatile memory such as hard-disk. Computer programs generally run on the RAM...

7 minutes read.