[英]Keyword argument in unpacking argument list/dict cases in 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'
為什么是這樣?
無論指定它們的順序如何,都會在關鍵字參數之前分配位置參數。 在您的情況下,位置參數是(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'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.