I. Parameter pass-through rule
Variable parameters allow 0 or any parameter to be passed in, automatically assembled into a tuple when the function is called;
The keyword parameter allows 0 or any parameter to be passed in, which is automatically assembled into a dict when the function is called;
1. Pass in the variable parameter:
1 def Calc (*numbers):2 sum = 03 for in Numbers:4 sum = SUM + n * n5 return sum
The above definition functions are used as follows:
Pass in multiple parameters,
Calc (1, 2, 3, 4)# function return value
Pass in a list,
Nums = [1, 2, 3]calc (# passes the element in the list as a mutable parameter to the function # function return value
2. Incoming keyword parameter:
>>>defPerson (name, age, * *kw): ..Print('Name:', Name,'Age :', Age,'Other :', kw) ...>>> >>> Person ('LUHC', city='Guangzhou') NAME:LUHC Age:Other: {' City':'Guangzhou'}
Similarly, you can pass a predefined dict as a parameter to the above functions:
>>> info = {' City':'Guangzhou','Job':'Engineer'}>>> >>> Person ('LUHC', 24, * *info) NAME:LUHC Age:Other: {' City':'Guangzhou','Job':'Engineer'}
Note: The function person obtains a copy of the parameter info, and the change within the function does not affect the value of info
3. In the keyword parameter, you can restrict the name of the keyword parameter:
#Specify key parameter names by * Split>>>defPerson (name, age, *, City, Job): ...Print('Name:', Name,'Age :', Age,'City :', City,'Job:', Job) ...>>> >>> Person ('LUHC', city='Guangzhou', job='Engineer') NAME:LUHC Age:24City:guangzhou Job:engineer#An exception is thrown if the parameter name is not within the defined range if passed in the argument>>> person ('LUHC', city='Guangzhou', jobs='Engineer') Traceback (most recent): File"<stdin>", Line 1,inch<module>Typeerror:person () got an unexpected keyword argument'Jobs'>>>
In addition, if a variable parameter is already specified in the function, the * can be omitted, as follows:
#omitted to use * as the partition, the name of the keyword parameter is specified>>>defPerson (name, age, *args, City, job): ...Print('Name:', Name,'Age :', Age,'args:', args,'City :', City,'Job:', Job) ...>>> >>> Person ('LUHC', 24,'a','b', city='Guangz', job='Engineer') NAME:LUHC Age:Args: ('a','b') City:guangz Job:engineer>>>#Similarly, if you pass in a parameter name that is not specified by the keyword argument, an exception is thrown>>> person ('LUHC', 24,'a','b', city='Guangz', job='Engineer', test='a') Traceback (most recent): File"<stdin>", Line 1,inch<module>Typeerror:person () got an unexpected keyword argument'Test'>>>
Two, the parameter combination uses:
The order of the parameter definitions must be: required, default, variable, named keyword, and keyword parameters
defF1 (A, B, c=0, *args, * *kw):Print('A ='A'B ='B'C ='C'args =', args,'kw =', kw)defF2 (A, B, c=0, *, D, * *kw):Print('A ='A'B ='B'C ='C'd ='D'kw =', kw)
Python--Function parameters