Say for example if I have a method which takes multiple inputs like below:
def SumOf(Arg1,Arg2,Arg3):
Sum = Arg1+Arg2+Arg3
return sum
I have the values of Arg1, Arg2, Arg3 in a list and I want to access the method
Arguments = Arg1 + "," + Arg2 + "," + Arg 3
I want to use the variable Arguments to call the method SumOf
SumOf(Arguments)
But I get the following error:
SumOf() takes exactly 3 arguments (1 given)
Note: The above is just an example, I need this for executing different methods based on the method name and arguments.
Please help.
We can pass multiple arguments to a python function by predetermining the formal parameters in the function definition.
The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-key worded, variable-length argument list. The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args.
By default, arguments may be passed to a Python function either by position or explicitly by keyword.
You can define Python function optional arguments by specifying the name of an argument followed by a default value when you declare a function. You can also use the **kwargs method to accept a variable number of arguments in a function. To learn more about coding in Python, read our How to Learn Python guide.
Arguments = 1, 2, 3
SumOf(*Arguments)
(*) operator will unpack the arguments to multiple parameters.
Looks like there's quite a few issues with your code. The line...
Arguments = Arg1 + "," + Arg2 + "," + Arg3
...suggests Arg1
, Arg2
and Arg3
are strings, which you're trying to concatenate into a single, comma-separated, string.
In order for the SumOf
function to work, it will need to be passed integer values, so if Arg1
, Arg2
and Arg3
are strings, you'll need to convert them to integers first with the int()
function, and pack them into a tuple, with something like...
Arguments = (int(Arg1), int(Arg2), int(Arg3))
...at which point you can call the function with either...
SumOf(*Arguments)
...or...
apply(SumOf, Arguments)
Additionally, you'll need to change the line...
return sum
...to...
return Sum
...otherwise you'll end up returning a reference to Python's built-in sum()
function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With