Have you ever wondered what happens when we define two functions with the same name but different numbers of parameters?
In languages like Java, this concept is called Function Overloading. Let's understand how Python handles this situation.
What Is Function Overloading?
Function overloading means defining multiple functions with the same name but different parameter lists.
The functions may differ based on:
- Number of parameters.
- Type of parameters.
- Order of parameters.
For example, in Java, we can define multiple methods with the same name but different parameters.
However, Python does not support traditional function overloading.
What Happens When We Define the Same Function Name Twice in Python?
Let's understand with an example.
def add(a, b):
print(a + b)
def add(a, b, c):
print(a + b + c)
add(10, 20)
add(10, 20, 30)
Output:
TypeError: add() missing 1 required positional argument: 'c'
Explanation
- First, we define the
add()function with two parameters. - Then, we define another
add()function with three parameters. - The second definition replaces the first function under the name
add. - When we call
add(10, 20), Python tries to execute the latest function definition. - But the latest function requires three arguments, and we provide only two.
Therefore, Python raises a TypeError.
How Can We Achieve Similar Functionality in Python?
Although Python does not support traditional function overloading, we can achieve similar behavior using default arguments and *args.
Using Default Arguments
def add(a, b, c=0):
print(a + b + c)
add(10, 20)
add(10, 20, 30)
Output:
30
60
Explanation:
- When we pass two arguments,
ctakes its default value0. - When we pass three arguments, the given value is assigned to
c.
Difference Between Java and Python
| Java | Python |
|---|---|
| Supports traditional method overloading. | Does not support traditional function overloading. |
| Multiple methods can have the same name with different parameter lists. | A later function definition with the same name replaces the earlier binding. |
| The compiler determines the appropriate overloaded method. | Default arguments and *args can provide similar flexibility. |
Top comments (0)