In Python, these two are mutable parameters in Python, *arg represents any number of nameless arguments, and the type Tuple;**kwargs represents the keyword argument, which is dict.
#* allows you to pass in 0 or any of these parameters, which are automatically assembled as a tuple when the function is called. defF (a,*args):Print(args) F (1,2,3,4)defCalc (*numbers): Sum=0 forNinchNumbers:sum= SUM + N *NPrint(sum) calc (1,2,3,4)#* *, the keyword parameter allows you to pass in 0 or any parameter with parameter names, which are automatically assembled into a dict within the function. defD (* *Kargs):Print(Kargs) d (a=1,b=2)#Mixed Use * and * * in functions. defH (a,*args,**Kargs):Print(A,args,kargs) H (1,2,3,x=4,y=5)defPerson (name,age,**kw):Print('Name:', Name,'Age :', Age,'Other :', kw) person ('Adam', gender=,'M', job='Engineer')
Output:
(2, 3, 4) 30{' A ': 1, ' B ': 2}1 (2, 3) {' X ': 4, ' y ': 5}name:adam age:45 Other: {' Gender ': ' M ', ' job ': ' Engineer '}
Knowledge Points:
In Python, when the * and * * symbols appear in a function-defined parameter, any number of parameter collections are represented. *arg represents any number of nameless arguments, the type Tuple;**kwargs represents the keyword argument, and dict is used when you need to place *arg before **kwargs, otherwise "Syntaxerror:non-keyword Arg after Keyword arg "syntax error
The above is the * and * * form written at the time of the function definition, which in turn, what if the * and * * syntax appear in the function call?
He will unpack the collection of parameters. For example, we can use the * syntax when calling a function, in which case, instead of the definition of a function, he will unpack the collection of parameters rather than creating a set of parameters.
#pass four parameters to a function through a tuple, and let Python unpack them into different parameters. deffunc (a,b,c,d):Print(a,b,c,d) a= (1,2,3,4)
Func (*a)#If there is already a meta-ancestor, add * to the argument, the function will pass the elements of the progenitor into the function .defCalc (*numbers): Sum=0 forNinchNumbers:sum= SUM + N *NPrint(sum) num= (1,2,3,4)Calc (*num)#If there is already a dict, precede the arguments with a * *, the function will convert all key-value pairs in the dict to the keyword parameters to pass indefPerson (name,age,**kw):Print('Name:', Name,'Age :', Age,'Other :', kw)Extra = {' City':'Beijing','Job':'Engineer'}person ('Jack', **extra)
Output:
1 2 3 4
30
Name:jack age:24 Other: {' City ': ' Beijing ', ' job ': ' Engineer '}
Knowledge Points:
When a function is called, a primitive is unpacked as a single element, making it a separate argument.
When a function is called, * * The dictionary is unpacked as a key/value pair, making it a separate keyword parameter.
The use of the "python-parameter" *arg and the **kwargs parameter