[python] *args **kwargs
Source code is as below:
1 def func(*args,**kwargs): 2 print 'args=',args 3 print 'kwargs=',kwargs 4 print '_'*30 5 6 def main(): 7 func(1,2,3,4) 8 func(a=1,b=2,c=3) 9 func(1,2,3,4,a=1,b=2,c=3) 10 func('a',1,None,a=1,b='2',c=3) 11 12 if __name__=='__main__': 13 main()
When the above code is executed,it produces the following result.
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'}
______________________________
*args representing a tuple()
**kwargs representing a dict()
*args and **kwagrs are used simultaneously,it should put *args as first argument followed by the **kwargs, instead,if the order is reversed,the error exception will be raised ,it should be like this:“SyntaxError: non-keyword arg after keyword arg”。
Tips and tricks:
one another way of using this is to create and generate dict()
def my_dict(**kwargs):
return kwargs
print my_dict(a=1,b=2,c=3)
{a=1,b=2,c=3}
dict(a=1,b=2,c=3) can generate a dict as well.