2010-06-29 78 views
5

对于python,我可以使用如下的解包参数。在Python中解压参数列表/字典案例中的关键字参数

def hello(x, *y, **z): 
    print 'x', x 
    print 'y', y 
    print 'z', z 

hello(1, *[1,2,3], a=1,b=2,c=3) 
hello(1, *(1,2,3), **{'a':1,'b':2,'c':3}) 
 
x = 1 
y = (1, 2, 3) 
z = {'a': 1, 'c': 3, 'b': 2} 

但是,我如果我使用关键字参数如下得到一个错误。

hello(x=1, *(1,2,3), **{'a':1,'b':2,'c':3}) 
TypeError: hello() got multiple values for keyword argument 'x'

这是为什么?

回答

9

无论指定它们的顺序如何,位置参数都是在关键字参数之前分配的。在你的情况下,位置参数是(1, 2, 3),关键字参数是x=1, a=1, b=2, c=3。由于首先分配了位置参数,参数x收到1,并且不再有资格获取关键字参数。这听起来有点奇怪,因为语法上你的位置参数在关键字参数之后被指定为,但是仍然遵守“位置参数→关键字参数”的顺序。

下面是一个简单的例子:

>>> def f(x): pass 
... 
>>> f(1, x=2) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: f() got multiple values for keyword argument 'x' 
>>> f(x=2, *(1,)) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: f() got multiple values for keyword argument 'x'