Try it here
Python OOPs Concept

Python Overloading


In the method overloading, methods or functions must have the same name and different signatures.

Consider below example:

>>> def add(a, b):
	return a + b

>>> def add(a, b, c):
	return a + b + c

>>> add(4, 5)
Traceback (most recent call last):
  File "", line 1, in 
    add(4, 5)
TypeError: add() missing 1 required positional argument: 'c'

It is because Python keeps only the latest definition of a method you declare to it. This code doesn't make a call to the version of add() that takes in two arguments to add. So we find it safe to say Python doesn’t support method overloading.

But to make this happen in Pythonic way, we can write the function like below.

>>> def add(instanceOf, *args):
	if instanceOf == 'int':
		res = 0
	if instanceOf == 'str':
		res = ''
	for i in args:
		res += i
	return res

>>> add('int', 1, 2, 3)
>>> add('int', 1, 2)
>>> add('str', 'Hello', ' World')
'Hello World'

It is to note that it isn't method overloading but simply use of default arguments.

Writer profile pic

Venkat on Sep 01, 2020 at 12:09 am

This article is contributed by Venkat. If you like and would like to contribute, you can write your article here or mail your article to . See your article appearing on the main page and help others to learn.

Post Comment

Comments( 0)


Forgot Password

Please enter your email address below and we will send you information to change your password.