开发者

what does "*" mean in Python?

开发者 https://www.devze.com 2023-01-31 13:22 出处:网络
I came across with a line in python. self.window.resize(*self.winsize) What does the \"*\" mean in this line?

I came across with a line in python.

            self.window.resize(*self.winsize)

What does the "*" mean in this line? I haven't 开发者_开发问答seen this in any python tutorial.


One possibility is that self.winsize is list or tuple. The * operator unpacks the arguments out of a list or tuple.

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

Ah: There is an SO discussion on this: Keyword argument in unpacking argument list/dict cases in Python

An example:

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

So unpacks elements out of list or tuple. Element can be anything.

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

Another small addition : If a function expects explicit number of arguments then the tuple or list should match the number of elements required.

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

To accept multiple arguments without knowing number of arguments:

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


Here, self.winsise is a tuple or a list with exactly the same number of elements as the number of arguments self.window.resize expects. If the number is either less or more, an exception will be raised.

That said, we can create functions to accept any number of arguments using similar trick. See this.


It doesn't have to be a tuple or list, any old (finite) iterable thing will do.

Here is an example passing in a generator expression

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号