+ 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))

2nd May 2022, 5:18 PM
Subhadeep Mandal
Subhadeep Mandal - avatar
8 Respostas
+ 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
2nd May 2022, 5:30 PM
Sousou
Sousou - avatar
+ 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)
2nd May 2022, 5:24 PM
Denise Roßberg
Denise Roßberg - avatar
+ 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
2nd May 2022, 5:32 PM
Slick
Slick - avatar
+ 3
You can pass a variable number if arguments to a function: https://code.sololearn.com/cyYksOK8uF4c/?ref=app
2nd May 2022, 5:38 PM
Lisa
Lisa - avatar
+ 1
Thankyou all and Thank you Sousou this is exactly what I wanted.
3rd May 2022, 2:42 AM
Subhadeep Mandal
Subhadeep Mandal - avatar
0
You cant in python
3rd May 2022, 8:37 PM
underscore
underscore - avatar
0
Hi can anyone help me in c++
3rd May 2022, 10:15 PM
Sabrina Akther Chowdhury