What do * and ** before a variable name mean in a function signature?
Possible Duplicate:
Understanding kwargs in Python
I have read a piece of python code, and I don't know what does * and ** mean in this code :
def functionA(self, *a, **kw):
// code here
I just know about one use of *: extract all attribute it has to parameter of method or constructor.
If this true for above function, so what does the rest : ** ?
Inside a function header :
*
collects all the positional arguments in a tuple
**
collects all the keyword arguments in a dictionary
>>> def functionA(*a, **kw):
print(a)
print(kw)
>>> functionA(1, 2, 3, 4, 5, 6, a=2, b=3, c=5)
(1, 2, 3, 4, 5, 6)
{'a': 2, 'c': 5, 'b': 3}
In a function call :
*
unpacks an list or tuple into position arguments
**
unpacks an dictionary into keyword arguments
>>> lis=[1, 2, 3, 4]
>>> dic={'a': 10, 'b':20}
>>> functionA(*lis, **dic) #it is similar to functionA(1, 2, 3, 4, a=10, b=20)
(1, 2, 3, 4)
{'a': 10, 'b': 20}
**
takes specified argument names and puts them into a dictionary. So:
def func(**stuff):
print(stuff)
func(one = 1, two = 2)
Would print:
{'one': 1, 'two': 2}
**
means named arguments of the functions.
$ cat 2.py
def k(**argv):
print argv
k(a=10, b = 20)
$ python 2.py
{'a': 10, 'b': 20}
argv
is a dictionary that contains all named arguments of the function.
And you can also reverse it. You can use a dictionary as a set of aruments for a function:
def k(a=10, b=20):
print a
print b
d={'a':30,'b':40}
k(**d)
would print
30
40
链接地址: http://www.djcxy.com/p/26772.html
上一篇: 一个系列的真值不明确。 使用a.empty,a.bool(),a.item(),a.any
下一篇: 变量名称在函数签名中的含义是什么?