Simple Python variable parameters, python variable parameters
1 def total (a = 5, * numbers, ** phonebook): 2 print ('A', a) 3 # traverse all items in the tuples 4 for single_item in numbers: 5 print ('single _ item', single_item) 6 # traverse all the items in the dictionary 7 for first_part, second_part in phonebook. items (): 8 print (first_part, second_part) 9 print (total (1123, 2231, Jack = 1560, John =, Inge = ))
1 a 102 single_item 13 single_item 24 single_item 35 Inge 15606 John 22317 Jack 11238 None
Positional Arguments) will be collected and aggregated into a Tuple called "param ). Similarly, when we declare a double star parameter such as ** param, all the keyword parameters starting and ending from then on will be collected and aggregated into a Dictionary named param (Dictionary ).
* Args
1 def argsFunc(a, *args):2 print a3 print args4 5 >>> argsFunc(1, 2, 3, 4)6 17 (2, 3, 4)
argsFunc
Matching the defined parameters,The remaining parameters are stored in args as tuples.(You can customize the args name). Therefore, in the above program, this function will accept as long as you input no less than 1 parameter. Of course, you can also directly define to accept only variable parameters, you can freely pass your parameters:
1 def argsFunc(*my_args):2 print my_args3 4 >>> argsFunc(1, 2, 3, 4)5 (1, 2, 3, 4)6 >>> argsFunc()7 ()
It's easy to put it in another form of variable parameters.
** Kwargs
The parameter name is represented by "*" before the parameter name. The parameter is stored in the function as an identifierdictionary
.arg1=value1,arg2=value2
This form.
To distinguish, I set* ArgsAs an array parameter,** KwargsCalled as Dictionary Parameter
>>> Def a (** x): print x >>> a (x = 1, y = 2, z = 3) {'y': 2, 'X': 1, 'z': 3} # store in the dictionary
However, you must note that when using ** kwargs to pass Parameters, you cannot pass array parameters.
>>> A (1, 2, 3) # Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: a () takes exactly 0 arguments (3 given)