【Python—參數】*arg與**kwargs參數的用法

來源:互聯網
上載者:User

標籤:beijing   gen   pre   可變參數   span   div   margin   log   調用函數   

在python中,這兩個是python中的可變參數,*arg表示任意多個無名參數,類型為tuple;**kwargs表示關鍵字參數,為dict。


# *允許你傳入0個或任意個參數,這些可變參數在函數調用時自動組裝為一個tuple。def f(a,*args):    print(args)f(1,2,3,4)def calc(*numbers):    sum = 0    for n in numbers:        sum = sum + n * n    print(sum)calc(1,2,3,4)# **,關鍵字參數允許你傳入0個或任意個含參數名的參數,這些關鍵字參數在函數內部自動組裝為一個dict。def d(**kargs):    print(kargs)    d(a=1,b=2)#在函數混合使用*以及**。def h(a,*args,**kargs):    print(a,args,kargs)h(1,2,3,x=4,y=5)def person(name,age,**kw):    print(‘name:‘,name,‘age:‘,age,‘other:‘,kw)    person(‘Adam‘, 45, gender=‘M‘, job=‘Engineer‘)
輸出:
(2, 3, 4)30{‘a‘: 1, ‘b‘: 2}1 (2, 3) {‘x‘: 4, ‘y‘: 5}name: Adam age: 45 other: {‘gender‘: ‘M‘, ‘job‘: ‘Engineer‘}

 

知識點:

在python中,當*和**符號出現在函數定義的參數中時,表示任意數目參數收集。*arg表示任意多個無名參數,類型為tuple;**kwargs表示關鍵字參數,為dict,使用時需將*arg放在**kwargs之前,否則會有“SyntaxError: non-keyword arg after keyword arg”的語法錯誤

 

上面是在函數定義的時候寫的*和**形式,那反過來,如果*和**文法出現在函數調用中又會如何呢?

他會解包參數的集合。例如,我們在調用函數時能夠使用*文法,在這種情況下,它與函數定義的意思相反,他會解包參數的集合,而不是建立參數的集合。 


#通過一個元組給一個函數傳遞四個參數,並且讓python將它們解包成不同的參數。def func(a,b,c,d):    print(a,b,c,d)a = (1,2,3,4)
func(*a)# 如果已經有一個元祖,在參數前加*,函數會把元祖中的元素一個一個傳到函數裡面def calc(*numbers): sum = 0 for n in numbers: sum = sum + n * n print(sum)num = (1,2,3,4)calc(*num)#如果已經有一個dict,在參數前面加**,函數會把dict中所有索引值對轉換為關鍵字參數傳進去def person(name,age,**kw): print(‘name:‘,name,‘age:‘,age,‘other:‘,kw)extra = {‘city‘: ‘Beijing‘, ‘job‘: ‘Engineer‘}person(‘Jack‘, 24, **extra)
輸出:
1 2 3 4
30
name: Jack age: 24 other: {‘city‘: ‘Beijing‘, ‘job‘: ‘Engineer‘}

 

知識點:

在函數調用時,*會以單個元素的形式解包一個元祖,使其成為獨立的參數。

在函數調用時,**會以鍵/值對的形式解包一個字典,使其成為獨立的關鍵字參數。

 

【Python—參數】*arg與**kwargs參數的用法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.