【问题标题】:what does "*" mean in Python?Python中的“*”是什么意思?
【发布时间】:2010-12-22 05:18:36
【问题描述】:

我在 python 中遇到了一行。

            self.window.resize(*self.winsize)

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

【问题讨论】:

标签: python


【解决方案1】:

一种可能性是 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')
>>>

【讨论】:

  • @Falmarri:非常感谢!我不确定,也不想让所有人都知道。
  • @lyrae:一点也不。它将与任何作为列表或元组的元素一起使用。试试看。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    它不必是元组或列表,任何旧的(有限的)可迭代的东西都可以。

    这是一个传入生成器表达式的示例

    >>> 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)
    

    【讨论】:

      猜你喜欢
      • 2010-09-29
      • 1970-01-01
      • 2012-01-23
      • 1970-01-01
      • 1970-01-01
      • 2014-06-03
      • 2015-02-13
      • 2013-05-20
      • 2010-10-23
      相关资源
      最近更新 更多