问题描述
与仅关键字参数功能在python3中配合使用时,我遇到了一些困难行为href ="https://docs.python.org/3.4/library/functools.html#functools.partial">部分.其他仅关键字参数的信息.
I am having some difficulty behaviour of keyword only arguments feature in python3 when used with partial. Other info on keyword only arguments.
这是我的代码:
def awesome_function(a = 0, b = 0, *, prefix):
print('a ->', a)
print('b ->', b)
print('prefix ->', prefix)
return prefix + str(a+b)
这是我对局部的理解:
>>> two_pow = partial(pow, 2)
>>> two_pow(5)
32
>>>
在上面的示例中,我理解的是,partial
使pow
的第二个参数成为two_pow
的唯一参数.
What I understood is in the above example, partial
makes the second argument to pow
function as the only argument of two_pow
.
我的问题是为什么以下各项起作用:
My question is why does the following work:
>>> g = partial(awesome_function, prefix='$')
>>> g(3, 5)
a -> 3
b -> 5
prefix -> $
'$8'
>>>
但是我得到了错误:
>>> awesome_function(prefix='$', 3, 5)
File "<stdin>", line 1
SyntaxError: non-keyword arg after keyword arg
>>>
我知道我可以直接致电awesome_function
,
I know that I can call awesome_function
directly by
>>> awesome_function(prefix='$', a = 3, b = 5)
a -> 3
b -> 5
prefix -> $
'$8'
>>>
推荐答案
根据 Python中的函数调用,要传递的参数的规则如下
As per the semantics of the function calls in Python, the rules for the arguments to be passed are as follows
argument_list ::= positional_arguments ["," keyword_arguments]
["," "*" expression] ["," keyword_arguments]
["," "**" expression]
| keyword_arguments ["," "*" expression]
["," keyword_arguments] ["," "**" expression]
| "*" expression ["," keyword_arguments] ["," "**" expression]
| "**" expression
如您在此处看到的,位置参数应始终出现在函数调用的开头.它们不能出现在其他任何地方.当你做
As you see here, the positional arguments should always appear at the beginning of the function calls. They cannot appear anywhere else. When you do
awesome_function(prefix='$', 3, 5)
它违反了上述规则,因为您在关键字参数(prefix
)之后传递了两个位置参数(3
和5
).这就是为什么得到SyntaxError
的原因,因为Python无法解析函数调用表达式.
it violates the above rule, as you are passing two positional arguments (3
and 5
) after a keyword argument (prefix
). That is why you are getting a SyntaxError
, as Python is not able to parse the function call expression.
但是,当您使用partial
时,它可以工作,因为partial
创建了一个新的函数对象,并存储了所有要传递给它的参数.实际调用partial
返回的函数对象时,它将首先应用所有位置参数,然后应用关键字参数.
But, when you are using partial
it works, because partial
creates a new function object and it stores all the parameters to be passed to it. When you actually invoke the function object returned by partial
, it applies all the positional arguments first and then the keyword arguments.
这篇关于了解"*"“仅关键字"; python3函数中的参数表示法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!