2010-12-22 119 views
2

我在Python中遇到了一條線。「*」在Python中的含義是什麼?

  self.window.resize(*self.winsize) 

「*」在這一行中的含義是什麼? 我還沒有在任何python教程中看到這個。

+1

見[開箱參數列表(http://docs.python.org/tutorial/controlflow.html?highlight=unpacking#unpacking-argument-列表)在線[Python教程](http://docs.python.org/tutorial/index.html)。 – martineau 2010-12-22 05:29:02

+0

另請參閱http://stackoverflow.com/questions/4496712/better-way-of-handling-nested-list/4497363#4497363。 – 2010-12-22 07:05:54

+0

可能的重複[對Python參數有什麼**和*做什麼](http://stackoverflow.com/questions/36901/what-does-and-do-for-python-parameters) – sth 2011-11-06 16:14:07

回答

8

一種可能性是self.winsize是列表或元組。 *運算符將參數從列表或元組中解開。

參見:http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists

啊:有一個SO討論這個:Keyword argument in unpacking argument list/dict cases in Python

一個例子:

>>> def f(a1, b1, c1): print a1 
... 
>>> a = [5, 6, 9] 
>>> f(*a) 
5 
>>> 

所以解壓出來的元素列表或元組。元素可以是任何東西。

>>> a = [['a', 'b'], 5, 9] 
>>> f(*a) 
['a', 'b'] 
>>> 

另一個小此外:如果一個函數需要的參數明顯的編號,則元組或列表應匹配所需的元件數量。

>>> a = ['arg1', 'arg2', 'arg3', 'arg4'] 
>>> f(*a) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: f() takes exactly 3 arguments (4 given) 
>>> 

要接受多個參數不知道數量的參數:

>>> def f(*args): print args 
... 
>>> f(*a) 
('arg1', 'arg2', 'arg3', 'arg4') 
>>> 
2

這裏,self.winsise是一個元組或相同數量元素的參數self.window.resize預計數量的列表。如果數量少或多,則會引發異常。

也就是說,我們可以使用類似的技巧創建函數來接受任意數量的參數。見this

2

它不一定是一個元組或列表,任何舊的(有限的)可迭代的東西都可以。

這裏是一個例子通過在發電機中表達

>>> def f(*args): 
...  print type(args), repr(args) 
... 
>>> f(*(x*x for x in range(10))) 
<type 'tuple'> (0, 1, 4, 9, 16, 25, 36, 49, 64, 81)