functools.partial希望使用位置参数作为关键字参数 [英] functools.partial wants to use a positional argument as a keyword argument
问题描述
所以我想了解partial
:
import functools
def f(x,y) :
print x+y
g0 = functools.partial( f, 3 )
g0(1)
4 # Works as expected
在:
g1 = functools.partial( f, y=3 )
g1(1)
4 # Works as expected
在:
g2 = functools.partial( f, x=3 )
g2(1)
TypeError: f() got multiple values for keyword argument 'x'
如果我将y
用作关键字参数,则TypeError
会消失:
The TypeError
disappears if I use y
as a keyword argument:
在:
g2( y=1 )
4
什么原因导致TypeError
?
推荐答案
这与functools.partial
无关.您实质上是这样调用函数的:
This has nothing to do with functools.partial
, really. You are essentially calling your function like this:
f(1, x=3)
Python首先满足位置参数,而您的第一个参数是x
.然后应用关键字参数,并且您再次 提供了x
.
Python first fulfils the positional arguments, and your first argument is x
. Then the keyword arguments are applied, and you again supplied x
.
functools.partial()
无法检测到您已经提供了第一个位置参数作为关键字参数.不会通过用y=
关键字参数替换位置参数来增加通话量.
functools.partial()
has no means to detect that you already supplied the first positional argument as a keyword argument instead. It will not augment your call by replacing the positional argument with a y=
keyword argument.
在混合使用位置参数和关键字参数时,必须注意不要重复使用同一参数.
When mixing positional and keyword arguments, you must take care not to use the same argument twice.
这篇关于functools.partial希望使用位置参数作为关键字参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!