Confused about ** parameters in python function calls
This question already has an answer here:
if neg:
That line is buggy. It should be:
if options["neg"]:
How does the function know when values ends and when options begins?
Unnamed values go in *values
. Keyword arguments go in **options
.
You have made a small mistake. Change your code to the following and it should work. Just get the value of "neg"
from the options
dictionary, ( values
holds the unnamed arguments and options
holds the keyword arguments)
>>> def sum(*values, **options):
s = 0
for i in values:
s = s + i
if "neg" in options:
if options["neg"]:
s = -s
return s
>>> s = sum(1, 2, 3, 4, 5, neg=True)
>>> s
-15
>>> sum(1, 2, 3, 4, 5)
15
>>> sum(1, 2, 3, 4, 5, neg=True)
-15
>>> sum(1, 2, 3, 4, 5, neg=False)
15
Although, as @glglgl pointed out, changing your code to the following consumes both the if
statements into one.
>>> def sum(*values, **options):
s = 0
for i in values:
s = s + i
if options.get("neg", False):
s = -s
return s
How does get(...)
work?
If the options
dictionary doesn't have a key "neg"
, (as handled by your first if condition), then, get(...)
returns the default value of False
and s
is not negated, and if options
contains "neg"
, then it's value is returned, in which case, s
is negated depending on the value in the dictionary.
上一篇: 直接将函数参数传递给cls()