2010-12-07 49 views
4

在方法簽名中是否有用於組合** kwargs和關鍵字參數的用法?在方法簽名中結合使用** kwargs和關鍵字參數

>>> def f(arg, kw=[123], *args, **kwargs): 
... print arg 
... print kw 
... print args 
... print kwargs 
... 
>>> f(5, 'a', 'b', 'c', kw=['abc'], kw2='def') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: f() got multiple values for keyword argument 'kw' 

好像沒用,但也許有人已經爲它找到一個很好的把戲......

+0

-1:不好的例子。參見@ Falmarri的回答。 – 2010-12-07 01:09:03

+1

如果你看了這個問題,我顯然沒有一個好的例子。 – explodes 2010-12-30 22:03:19

+0

@ S.Lott一個不好的例子是沒有理由downvote。如果OP完全徹底地理解了這個話題,他就不用問了。 – 2016-07-16 17:51:21

回答

9

你兩次分配千瓦。

在這個調用f(5, 'a', 'b', 'c', kw=['abc'], kw2='def'),arg = 5,kw ='a',* args =('b','c'),然後您嘗試再次分配kw。

12

在Python 3中,您可以擁有關鍵字參數(PEP 3102)。有了這些,你的函數應該是這樣的:

>>> def f(arg, *args, kw=[123], **kwargs): 
... print(arg) 
... print(kw) 
... print(args) 
... print(kwargs) 
>>> f(5, 'a', 'b', 'c', kw=['abc'], kw2='def') 
5 
('a', 'b', 'c') 
['abc'] 
{'kw2': 'def'} 

(請注意,雖然我改變的參數的順序我沒有改變print S的順序。)

在Python 2,你可以」 t在varargs參數後面有一個關鍵字參數,但是在Python 3中,您可以,並且它使得該參數僅爲關鍵字。請注意0​​。

相關問題