【问题标题】:Keyword argument in unpacking argument list/dict cases in PythonPython中解包参数列表/字典案例中的关键字参数
【发布时间】:2011-03-09 15:24:43
【问题描述】:

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

这是为什么?

【问题讨论】:

    标签: python argument-passing


    【解决方案1】:

    无论指定它们的顺序如何,位置参数都会在关键字参数之前分配。在您的情况下,位置参数是(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'
    

    【讨论】:

      猜你喜欢
      • 2017-11-26
      • 2013-08-07
      • 2020-05-07
      • 2017-08-08
      • 1970-01-01
      • 2020-09-11
      • 2013-08-16
      • 2016-12-26
      • 1970-01-01
      相关资源
      最近更新 更多