在 Python 中解包参数列表/字典案例中的关键字参数 [英] Keyword argument in unpacking argument list/dict cases in Python

查看:66
本文介绍了在 Python 中解包参数列表/字典案例中的关键字参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于 python,我可以使用如下解包参数.

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

<前>x = 1y = (1, 2, 3)z = {'a':1,'c':3,'b':2}

但是,如果我按如下方式使用关键字参数,则会出现错误.

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

TypeError: hello() 得到了多个关键字参数x"的值

这是为什么?

解决方案

无论指定的顺序如何,位置参数都会在关键字参数之前分配.在您的情况下,位置参数是 (1, 2, 3),关键字参数是 x=1, a=1, b=2, c=3.因为位置参数首先被分配,参数 x 接收 1 并且不再符合关键字参数的条件.这听起来有点奇怪,因为在语法上你的位置参数是在关键字参数之后指定的,但始终遵循位置参数→关键字参数"的顺序.

这是一个更简单的例子:

<预><代码>>>>def f(x): 通过...>>>f(1, x=2)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:f() 为关键字参数x"获得了多个值>>>f(x=2, *(1,))回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:f() 为关键字参数x"获得了多个值

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?

解决方案

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'

这篇关于在 Python 中解包参数列表/字典案例中的关键字参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆