When the parameter of a function is preceded by an asterisk * The time expression is a variable position parameter , Two asterisks ** Indicates variable keyword parameters
You can package the parameters passed by the function ( Tuples tuple Or a dictionary dictionary), Can also break up ( Decompose into individual elements ), The packing and unpacking of tuples use a single star *, The dictionary is packed and disassembled with double line numbers **
pack , Is any number of... That will be passed to the function ( It could be zero ) Non key parameters / Keyword parameters are packaged into a tuple / Dictionaries ( Tuples can only accept non keyword parameters , The dictionary can only accept keyword parameters )
The code is as follows ( Example ):
def param(*args, **kwarg):
for i in args:
print(i)
for i,j in kwarg.items():
print(j, j)
print('*' * 20)
if __name__ == '__main__':
param(1, 2, a=4, b=5)
param(2, 3, a=1, b=2, c=3)
Return results :
1
2
4 4
5 5
********************
2
3
1 1
2 2
3 3
********************
Process finished with exit code 0
Unpack , Is a list that will be passed to the function 、 Tuples or dictionaries are split into independent elements and assigned to parameter variables in functions ( Including ordinary position parameters , Key parameters , Tuples , Dictionary, i.e ** Key parameters )
The code is as follows ( Example ):
def param(*args, **kwarg):
for i in args:
print(i)
for i,j in kwarg.items():
print(j, j)
print('*' * 20)
if __name__ == '__main__':
a = (1, 2, 3)
b = [1, 16, 22]
c = {
'a':11, 'b':13}
param(a, c)
param(*a, **c)
param(b, c)
param(*b, **c)
Return results :
# explain :param(a, c) Output a and b
(1, 2, 3)
{
'a': 11, 'b': 13}
********************
# explain :param(*a, **c) Break up a and c
1
2
3
11 11
13 13
********************
# explain :param(b, c) Output b and c
[1, 16, 22]
{
'a': 11, 'b': 13}
********************
# explain :param(*b, **c) Break up b and c
1
16
22
11 11
13 13
********************