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 : ** ?
The asterisk (star) operator is used in Python with more than one meaning attached to it. For numeric data types, * is used as multiplication operator >>> a=10;b=20 >>> a*b 200 >>> a=1.5; b=2.5; >>> a*b 3.75 >>> a=2+3j; b=3+2j >>> a*b 13j.
Here single asterisk( * ) is also used in *args. It is used to pass a variable number of arguments to a function, it is mostly used to pass a non-key argument and variable-length argument list.
Python callables have a signature: the interface which describes what arguments are accepted and (optionally) what kind of value is returned. The function func (above) has the signature (a, b, c) . We know that it requires three arguments, one for a , b and c . These ( a , b and c ) are called parameters.
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 a list or tuple into position arguments.
**
unpacks a 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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With