In this tutorial we will learn about method overloading in Python.
We learned about method overriding in the Python - Method Overriding tutorial. Feel free to check that out.
In Python we can create a method that can be called in different ways.
So, we can have a method that has zero, one or more number of parameters and depending on the method definition we can call it with zero, one or more arguments.
This is method overloading in Python.
Point to note!
Method overloading in Python is achieved by using one method with different number of arguments.
In other programming languages like Java we have more than one method definition for the same method name to achieve method overloading in Java.
In the following Python program we are overloading the area method.
If there is no argument then it returns 0.
If we have one argument then it returns square of the value and assumes you are computing the area of a square.
And if we have two arguments then it returns the product of the two values and assumes you are computing the area of a rectangle.
# area method
def area(self, x = None, y = None):
if x != None and y != None:
return x * y
elif x != None:
return x * x
obj = Compute()
# zero argument
# one argument
# two argument
print("Area:", obj.area(4, 5))
The above code will give us the following output.
Have fun learning :-)
Copyright © 2014 - 2019 DYclassroom. All rights reserved.
rendered in 0.0259 sec