How to perform method overloading in python / Why method overloading is not supported in python

What is method overloading
Method overloading in a class means having more than one methods with same name but with different number or types of arguments. Following are the examples of overloaded methods in java

class OverloadingDemo {
   methodOne(int a) {}
   methodOne(String a) {}
   methodOne(int a, String b) {}
   methodOne(double a) {}
}

All of the above methods have same name but either different number or type of arguments.

Method overloading in python
Python does not support method overloading, that is, it is not possible to define more than one method with the same name in a class in python. This is because method arguments in python do not have a type. A method accepting one argument can be called with an integer value, a string or a double. Consider code sample below.

class OverloadDemo:
 
   # define single argument method
   def method(self, a):
      print(a)
 
# create object of class
obj = OverloadDemo()
# call method with integer argument
obj.method(5)
# call method with string argument
obj.method('codippa')
# call method with double argument
obj.method(10.2)

Output of above code will be

5
codippa
10.2

Same method works for 3 different data types. Thus, you cannot define two methods with the same name and same number of arguments but having different type as shown in the above example.  They will be treated as the same method.

Above example demonstrated the case when the arguments had different types but one might ask that overloading can also be performed when the number of arguments are different. This is also not possible because python treats all the methods with the same name as one method irrespective of the number of arguments. If there are more than one methods with same name then last method definition will over write the other even if they have different number of arguments, that is, python will only consider and the last method as if this is the only method present in the class as shown in below example.

class OverloadDemo:
 
    # define no argument method
    def method(self):
        print("No argument")
 
    # define 1 argument method
    def method(self, a):
        print("One argument")
 
    # define 2 argument method
    def method(self,a, b):
        print("Two arguments")
 
# create object of class
obj = OverloadDemo()
# call method with a single argument
obj.method(10)

Above code when executed will result in an error as

TypeError: method() missing 1 required positional argument: ‘b’

This is because the last method over writes the other two methods and only one method is present in the class which accepts two arguments but we supplied only 1 argument while calling. If the number of arguments of the last method do not match the number of arguments supplied while calling the method, it will be an error.
Alternative
Above explanation and code examples made it clear that method overloading is not supported in python but that does not mean that you cannot call a method with different number of arguments. There are a couple of alternatives available in python that make it possible to call the same method but with different number of arguments.

Using default argument values
It is possible to provide default values to method arguments while defining a method. If method arguments are supplied default values, then it is not mandatory to supply those arguments while calling method. Python considers the values of those arguments while executing the method. Example,

class OverloadDemo:
 
    # arguments with default values
    def default_arguments(self, a='codippa', b='the website'):
        print(a)
        print(b)
 
# create class object
obj = OverloadDemo()
# call method without arguments
obj.default_arguments()

Above code will produce the following output

codippa
the website

Above class defines a method with 2 arguments having default values and it is called without any arguments. Python utilizes those default values while executing the method.

It is not necessary to provide default values to all the arguments but if an argument is supplied a default value, then all the arguments towards its right should be supplied default values.

If argument values are supplied while calling the method then those values overwrite the default values as shown in below example

class OverloadDemo:
 
    # arguments with default values
    def default_arguments(self, a='codippa', b='the website'):
        print(a)
        print(b)
 
# create class object
obj = OverloadDemo()
# call method with arguments
obj.default_arguments('learning', 'python')

which produces following output

learning
python

Now the question arises “How using default values can be used to call method with different argument numbers?”. Following example shows that.

class OverloadDemo:
 
    def default_arguments(self, a = None, b = None, c = None):
        # check if all arguments have values
        if(a != None and b != None and c != None):
            print("3 arguments")
        # check if first two arguments have values
        elif (a != None and b != None):
            print("2 arguments")
        # check if first argument has value
        elif a != None:
            print("1 argument")
        else:
            print("0 arguments")
 
obj = OverloadDemo()
# call method with 3 arguments
obj.default_arguments('codippa', 'the', 'website')
# call method with 2 arguments
obj.default_arguments('codippa', 'website')
# call method with 1 argument
obj.default_arguments('codippa')
# call method with 0 argument
obj.default_arguments()

Above class contains a method with 3 arguments having default values as None. Default value of None means argument has not been explicitly provided a value.
Method checks the values of those arguments and performs accordingly. An object of this class is created and the method is called with 3, 2, 1 and 0 arguments and works well producing the output shown below.

3 arguments
2 arguments
1 argument
0 arguments

This shows that same method can be used with different number of arguments.

Using variable arguments
Python allows supplying varying number of arguments to a method using a special syntax. You just need to write one method argument preceded with an asterisk(*). An asterisk before an argument lets you supply 0 or more arguments to a method. Above example can be modified as below.

class OverloadDemo:
 
    def default_arguments(self, *a):
        print("0|1|2|3 arguments")
 
obj = OverloadDemo()
# call method with 3 arguments
obj.default_arguments('codippa', 'the', 'website')
# call method with 2 arguments
obj.default_arguments('codippa', 'website')
# call method with 1 argument
obj.default_arguments('codippa')
# call method with 0 argument
obj.default_arguments()

Notice the method defines only one argument preceded by a *. This lets you supply any number of arguments to it without any errors. This method is then called with different number of arguments producing the below output

0|1|2|3 arguments
0|1|2|3 arguments
0|1|2|3 arguments
0|1|2|3 arguments

When a method contains an argument preceded with a *, it accepts the values as a tuple internally.

Adding numbers using variable arguments
A practical example of using variable number of arguments would be to create a method that can add any number of integers. This way it will make possible to create a method that can accept different number of arguments. Example,

class OverloadDemo:
 
    def add(self, *a):
        # variable to hold sum of numbers
        sum = 0
        # iterate over the arguments
        for num in a:
            # add numbers
            sum = sum + num
        return sum
 
# create object of class
obj = OverloadDemo()
# call method with 5 arguments
sum = obj.add(1,2,3,4,5)
print("Sum of 5 numbers is "+str(sum))
# call method with 4 arguments
sum = obj.add(1,2,3,4)
print("Sum of 4 numbers is "+str(sum))
# call method with 3 argument
sum = obj.add(1,2,3)
print("Sum of 3 numbers is "+str(sum))
# call method with 0 argument
sum = obj.add()
print("Sum of 0 numbers is "+str(sum))

This produces the following output

Sum of 5 numbers is 15
Sum of 4 numbers is 10
Sum of 3 numbers is 6
Sum of 0 numbers is 0

As clear from above code, variable arguments lets you achieve method overloading in that you can have methods that accept different number of arguments but with only one method. Note that above method works for same type of arguments. If you have different type of arguments, then you have to handle this situation using your own logic.

Mark Your Impression

Close Menu