Define a function in Python, you can use required parameters, default parameters, variable parameters, and keyword parameters, all 4 parameters can be used together, or only some of them, but note that
The order of the parameter definitions must be: required, default, variable, and keyword parameters .
Take a look at the example code:
defFunc (a,b,c=0,*args,**kw):Print 'a='A'b='B'c='C'args=', args,'kw=', KW>>> func () A= 1 b= 2 c= 0 args= () kw= {}>>> func (All) A= 1 b= 2 c= 3 args= () kw= {}>>> func (1,2,4, (1,3,4,5)) a= 1 b= 2 c= 4 args= ((1, 3, 4, 5), kw= {}>>> func (1,2,4,11,22,33,44,55) A= 1 b= 2 c= 4 args= (one, one, one, one, one) kw= {}>>> func (1,2,4,11,22,33,44,55,{'x':'xx','y':'yy'}) a= 1 b= 2 c= 4 args= (11, 22, 33, 44, 55, {'y':'yy','x':'xx'}) kw= {}>>> func (1,2,4,11,22,33,44,55,x='xx', y='yy') A= 1 b= 2 c= 4 args= (one, one, one, one, one) kw= {'y':'yy','x':'xx'}
#you can write it like that.defFunc (a,b,c=0,*args,**kw):Print 'a='A'b='B'c='. cn'args=', args,'kw=', Kwargs= (1, 2, 3, 4) kw= {'x': 99}func (1,2,4,*args, * *kw) a= 2 b= 3 c= 4 args= (5, 6, 7, 8) kw= {'y': 100,'x': 99}
Summarize:
Be aware of the syntax for defining mutable parameters and keyword parameters:
*argsis a variable parameter, and args receives a tuple;
**kwis a keyword parameter, kw receives a dict.
And how to pass in the syntax for variable and keyword arguments when calling a function:
Variable parameters can be directly passed func(1, 2, 3) in:, you can first assemble a list or a tuple, and then pass in *args : func(*(1, 2, 3)) ;
Keyword parameters can be directly passed in: func(a=1, b=2) , you can first assemble dict, and then pass in **kw : func(**{‘a‘: 1, ‘b‘: 2}) .
Parameters in Python