Python Method Overloading¶
method overloading in python can be defined as writing the method in such a way that method will provide different functionality for different datatype arguments with the same method name. Programming languages like Java and C++ implements the method overloading by defining the two methods with the same name but different parameters. In python we do not implement *method overloading *in that way because Java and C++ languages are statically typed hence we need to specify the data types before compilation. But python is a dynamically typed language hence we can implement the same behavior with a same method in python.
How to overload a method in python?¶
Let's do some code to implement the method overloading in python.
class SayHello:
def hello(self, first_name=None, last_name=None):
if first_name and last_name:
print("Hello {0} {1} !".format(first_name, last_name))
elif first_name:
print("Hello {0} !".format(first_name))
else:
print("Hello !")
obj = SayHello()
obj.hello("Anjaneyulu", "Batta")
# Output: Hello Anjaneyulu Batta!
obj.hello("Anji")
# Output: Hello Anji !
obj.hello()
# Output: Hello !
In above code we have implemented method overloading for the method hello. After creating object we have called the method hello with two arguments first name "Anjaneyulu" and last name "Batta" and the method hello returned output Hello Anjaneyulu Batta !. In the next line we called the same method with a single argument name "Anji" now the method returned Hello Anji !. In the next line we have called the same method without the parameter now, the method returned the output Hello !.
In above code we can see that method hello is behaving differently for different parameters that means we are overloading the behavior of the method for different arguments.