Python中的“*”是什么意思?

时间:2010-12-22 05:18:37

标签: python

我在python中遇到过一行。

            self.window.resize(*self.winsize)

“*”在这一行中的含义是什么? 我没有在任何python教程中看到过这个。

3 个答案:

答案 0 :(得分:8)

一种可能性是self.winsize是list或tuple。 *运算符从列表或元组中解压缩参数。

请参阅:http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists

啊:有关于此的讨论: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')
>>>

答案 1 :(得分:2)

这里,self.winsise是一个元组或列表,其元素数量与参数self.window.resize所期望的数量完全相同。如果数量少或多,则会引发异常。

也就是说,我们可以使用类似的技巧创建接受任意数量参数的函数。请参阅this

答案 2 :(得分: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)
相关问题