Keyword argument in unpacking argument list/dict cases in Python

岁酱吖の 提交于 2019-11-30 05:44:58

问题


For python, I could use unpacking arguments as follows.

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?


回答1:


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. Because positional arguments get assigned first, the parameter x receives 1 and is not eligible for keyword arguments any more. 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'


来源:https://stackoverflow.com/questions/3141152/keyword-argument-in-unpacking-argument-list-dict-cases-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!