Home >Backend Development >Python Tutorial >Detailed explanation of Python's *args and **kwargs
*args represents any multiple unnamed parameters, which is a tuple; **kwargs represents keyword parameters, which is a dict.
def fun(*args, **kwargs): print 'args = ', args print 'kwargs = ', kwargs print '###' if __name__ == '__main__': foo(1,2,3,4) foo(a=1,b=2,c=3) foo(1,2,3,4, a=1,b=2,c=3) foo('a', 1, None, a=1, b='2', c=3)
The output result is as follows:
args = (1, 2, 3, 4) kwargs = {} ### args = () kwargs = {'a': 1, 'c': 3, 'b': 2} ### args = (1, 2, 3, 4) kwargs = {'a': 1, 'c': 3, 'b': 2} ### args = ('a', 1, None) kwargs = {'a': 1, 'c': 3, 'b': '2'} ###
As you can see, these two are variable parameters in python.
Note: When using *args and **kwargs at the same time, the *args parameter must be listed before **kwargs, like foo(a=1, b='2', c=3, a', 1, None, ) If called in this way, the syntax error "SyntaxError: non-keyword arg after keyword arg" will be prompted.
def fun2(param1, *args, **kwargs): print 'param1 = ', param1 print 'args = ', args print 'kwargs = ', kwargs print '###' fun2(1, 2, 3, 4, a=1,b=2,c=3)
Output result:
param1 = 1 args = (2,3,4) kwargs = {'a': 1, 'c': 3, 'b': 2} ###
1 is assigned to param1, the remaining 2, 3, and 4 are assigned to *args, and the others are assigned to **kwargs
There is also a very beautiful usage, which is to create a dictionary:
def kw_dict(**kwargs): return kwargs print kw_dict(a=1,b=2,c=3)
Result:
{'a':1, 'b':2, 'c':3}
In fact, there is a dict class in Python, use dict(a=1,b=2,c= 3) You can create a dictionary.