程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python] detailed unpacking of args and kwargs

編輯:Python

args And kwargs Unpacking details

 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])


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved