+ 5
How to do function overloading in python?
def add(x,y): return x+y def add(x,y,z): return x+y+z print(add(5,7))
8 Answers
+ 3
Subhadeep Mandal, creating a variable, function or class in python overwrites the previous variable with the same name, but if you want to use multiple args, see this example:
https://code.sololearn.com/cOkQT5RzFFBr/?ref=app
+ 4
Python does not support overloading.
You can define two functions with the same name, but the last one overrides the other.
In your case:
def add(x,y):
return x+y
#here you can call add(5,7)
def add(x,y,z):
return x+y+z
#here you can only call add(1,2,3)
+ 4
The only way it can be done is in subclasses.
class A:
def __init__(self):
self.val = 5
def print_val(self):
print(self.val)
class B(A):
def __init__(self):
super().__init__()
def print_val(self):
print(self.val * 2)
a = A()
b = B()
a.print_val()
b.print_val()
# output
5
10
+ 3
You can pass a variable number if arguments to a function:
https://code.sololearn.com/cyYksOK8uF4c/?ref=app
+ 1
Thankyou all and Thank you Sousou this is exactly what I wanted.
0
You cant in python
0
Hi can anyone help me in c++