简体   繁体   English

Python中解包参数列表/ dict案例中的关键字参数

[英]Keyword argument in unpacking argument list/dict cases in Python

For python, I could use unpacking arguments as follows. 对于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}

But, I got an error if I use keyword argument as follows. 但是,如果我使用关键字参数,我得到一个错误如下。

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

Why is this? 为什么是这样?

Regardless of the order in which they are specified, positional arguments get assigned prior to keyword arguments. 无论指定它们的顺序如何,都会在关键字参数之前分配位置参数。 In your case, the positional arguments are (1, 2, 3) and the keyword arguments are x=1, a=1, b=2, c=3 . 在您的情况下,位置参数是(1, 2, 3) ,关键字参数是x=1, a=1, b=2, c=3 Because positional arguments get assigned first, the parameter x receives 1 and is not eligible for keyword arguments any more. 因为首先分配位置参数,所以参数x接收1并且不再符合关键字参数的条件。 This sounds a bit weird because syntactically your positional arguments are specified after the keyword argument, but nonetheless the order “positional arguments → keyword arguments” is always adhered to. 这听起来有点奇怪,因为在语法上你的位置参数是关键字参数之后指定的,但是仍然遵守“位置参数→关键字参数”的顺序。

Here is a simpler example: 这是一个更简单的例子:

>>> 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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM