1def Total (a=5, *numbers, * *phonebook):2Print'a', a)3 #遍历元组中的所有项目4 forSingle_iteminchnumbers:5Print'Single_item', Single_item)6 #遍历字典中的所有项目7 forFirst_part, Second_partinchPhonebook.items ():8 print (First_part,second_part)9Print (Total (Ten,1,2,3, jack=1123, john=2231, inge=1560))
1 Ten 2 1 3 2 4 3 5 1560 6 2231 7 1123 8 None
When we declare an asterisk parameter such as *param, all positional parameters (positional Arguments) starting from here until the end are collected and aggregated into a tuple called "param" (tuple). Similarly, when we declare a double-star parameter such as **param, all the keyword parameters starting from here until the end are collected and aggregated into a dictionary called param (Dictionary).
*args
1 def argsfunc (A, *args):2 print a3 print args4 5 >>> argsfunc (1234)6 17 (234)
argsfunc matches the defined parameters, the remaining parameters are stored as tuples in args (args Name you can define yourself), so in the above program as long as you pass in not less than 1 parameters, the function will accept, of course, you can also directly define the only accept variable parameters, you can freely pass your arguments:
1 def argsfunc (*My_args):2 print My_args3 4 >> > Argsfunc (1234)5 (12 3 4 )6 >>> argsfunc ()7 ()
Very simply put, now come to another kind of indeterminate parameter form
**kwargs
The name of the formal parameter plus two * indicates that the parameter inside the function will be stored in the form named identifier dictionary , the method of calling the function needs to take arg1=value1,arg2=value2 this form.
To differentiate, I refer to *args as an array parameter,**kwargs called a dictionary parameter
>>> def a(**x):print x>>> a(x=1,y=2,z=3){‘y‘: 2, ‘x‘: 1, ‘z‘: 3} #存放在字典中
However, there is a need to note that you cannot pass array parameters when using **kwargs to pass parameters
>>> a(1,2,3) #这种调用则报错Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: a() takes exactly 0 arguments (3 given)
Concise python variable parameters