Yesterday i have explored two important concepts function overloading and return Keyword.
1.Function Overloading in Python
Function Overloading mean defining multiple functions with the same name but with different parameters.In Java function overloading it is supported directly.
Python does not support function overloading directly.
Example:
`def add(a,b):
print(a+b)
def add(a,b,c):
print(a+b+c)
add(10,20)`
python keeps the latest function add.
when we call add(10,20),Python raises a TypeError because latest definition expects three arguments.
We can achieve similar functionality in Python by using default arguments **or **variable-length arguments.
Using default arguments:
`def add(a,b,c=0):
print(a+b+c);
add(10,20)
add(10,20,30)`
**
Output:**
30
60
Here the default value c **is **zero. we provide a third argument it overrides the default value.
2.Return keyword?
it sends the value back to the caller of a function.
Example:
`def calculate():
return 20-30
result = calculate()
print(result)`
Output:
-10
- def calculate()- defines a function.
- return 20-30 calculates the result and send it back.
- result = calculate() calls the function and stores the returned value in the variable result.
- print(result) displays the value.
Main difference:
print() displays information on the screen.
return sends a value back to the caller.
we can store the return value in a variable and use it later.
if we call a function that uses return without printing or using its result a normal python script won't display the value.
I learnt some important factors:
- Python does not support traditional overloading directly.
- defining another function with the same name replaces previous function binding.
- Default arguments can help handle diffrent number of arguments.
- The return keyword sends a value back to the function caller.
- print() displays a value,whereas return gives a value back to the caller.
I understood that defining a function is not the same as calling a function and returning a value not same as displaying it.
Top comments (1)
The comparison is useful, especially because Python developers often arrive expecting Java-style overloads. One important addition is that the final function definition replaces earlier ones; the usual Python alternatives are default arguments, *args, keyword-only parameters, or singledispatch when the type-based behavior is genuinely needed. That distinction prevents a beginner from thinking several same-named functions are active at once.