But first, let me say * , Maybe at the beginning Python It is difficult to understand unpacking
C In language * Is an operation on a pointer , stay Python There is only one function in , Namely “ unpacking ”
“ unpacking ” As the name suggests, it means opening the package , Package ( Here, tuples Tuple、 Dictionaries Dictionary) The data inside is split into individual data .
for example :
numTuple = (1, 2, 3)
After unpacking :
1 2 3
First look at the following code :
# Python unpacking
def function1(value, *args):
print(value) # 1
print(args) # (1, 2, 3, 4)
print(*args) # 1, 2, 3, 4
# take args And 8args Pass as arguments
function2(args) # ((1, 2, 3, 4),) # (1, 2, 3, 4)
function2(*args) # (1, 2, 3, 4) # 1 2 3 4
def function2(*args):
print(args)
print(*args)
function1(1, 1, 2, 3, 4)
The implementation is as follows :
analysis :
1. function1(1, 1, 2, 3, 4) when ,value To receive the 1,args Received (1,2,3,4)
Be careful , yes args Received , No *args Received
2. * Is the unpacking instruction , So the output args It is not unpacked , That is, the original tuple print Of
3. Will be args As arguments to function2 when , That is, the tuple without unpacking is passed to the new element group in the form of an element
4. And will be *args As an argument , After unpacking , That is to say 1,2,3,4 Passed to... In four elements function2
It may be a little hard to understand at first , Just write more times .
If you have understood the above , So the next **kwargs At a glance
def function3(**kwargs):
print(kwargs)
for key in kwargs:
print(key)
print(kwargs[key])