1 def total (a=5, *numbers, **phonebook): 2 print (' A ', a) 3 #遍历元组中的所有项目4 for Single_item in Numbers:5 Print (' Single_item ', Single_item) 6 #遍历字典中的所有项目7 for First_part, Second_part in Phonebook.items (): 8 Print (First_part,second_part) 9 print (Total (10,1,2,3,jack=1123,john=2231,inge=1560))
1 A 102 Single_item single_item Inge 15606 John 22317 Jack 11238 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 (1, 2, 3, 4) 6 17 (2, 3, 4)
argsFuncAfter matching the defined parameters, the remaining parameters are stored in the form of a tuple in args(the args name you can define yourself), so as long as you pass in the above program not less than 1 parameters, the function will accept, of course, you can also directly define only accept variable parameters, You are free to pass on 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 ()
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