我在Python中遇到了一条线。“*”在Python中的含义是什么?
self.window.resize(*self.winsize)
“*”在这一行中的含义是什么? 我还没有在任何python教程中看到这个。
我在Python中遇到了一条线。“*”在Python中的含义是什么?
self.window.resize(*self.winsize)
“*”在这一行中的含义是什么? 我还没有在任何python教程中看到这个。
一种可能性是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')
>>>
这里,self.winsise
是一个元组或相同数量元素的参数self.window.resize
预计数量的列表。如果数量少或多,则会引发异常。
也就是说,我们可以使用类似的技巧创建函数来接受任意数量的参数。见this。
它不一定是一个元组或列表,任何旧的(有限的)可迭代的东西都可以。
这里是一个例子通过在发电机中表达
>>> 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)
见[开箱参数列表(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
另请参阅http://stackoverflow.com/questions/4496712/better-way-of-handling-nested-list/4497363#4497363。 – 2010-12-22 07:05:54
可能的重复[对Python参数有什么**和*做什么](http://stackoverflow.com/questions/36901/what-does-and-do-for-python-parameters) – sth 2011-11-06 16:14:07