2009-05-28 262 views
245

以類似的方式,使用在C或C++可變參數:可以將可變數量的參數傳遞給函數嗎?

fn(a, b) 
fn(a, b, c, d, ...) 
+5

我指的光榮lottness播客53:http://itc.conversationsnetwork.org/shows/detail4111.html?loomia_si=t0:a16:g2:r2: c0.246273:b24677090 – 2009-05-28 11:10:35

+1

我得和洛特先生一起去這個。您可以在Python文檔中快速獲得關於此文檔的授權答案,此外您還可以瞭解文檔中還有其他內容。如果您計劃使用Python,那麼瞭解這些文檔對您有好處。 – 2009-05-28 19:41:15

+7

最快的答案是Google說的最快的答案。 – 2013-04-02 07:13:18

回答

319

是。

這很簡單,如果你忽略關鍵字參數的工作原理:

def manyArgs(*arg): 
    print "I was called with", len(arg), "arguments:", arg 

>>> manyArgs(1) 
I was called with 1 arguments: (1,) 
>>> manyArgs(1, 2,3) 
I was called with 3 arguments: (1, 2, 3) 

正如你所看到的,Python將會給你的所有參數一個元組。

對於關鍵字參數,您需要將這些參數作爲單獨的實際參數接受,如Skurmedel's answer中所示。

+10

http://docs.python.org/tutorial/controlflow.html#more-on-defining-functions – Miles 2009-05-28 08:06:04

179

添加到退繞後:

您可以發送多個鍵值ARGS了。

def myfunc(**kwargs): 
    # kwargs is a dictionary. 
    for k,v in kwargs.iteritems(): 
     print "%s = %s" % (k, v) 

myfunc(abc=123, efh=456) 
# abc = 123 
# efh = 456 

你也可以混合使用這兩種:

def myfunc2(*args, **kwargs): 
    for a in args: 
     print a 
    for k,v in kwargs.iteritems(): 
     print "%s = %s" % (k, v) 

myfunc2(1, 2, 3, banan=123) 
# 1 
# 2 
# 3 
# banan = 123 

它們必須既聲明和調用的順序,也就是函數簽名必須是*指定參數時,** kwargs,並呼籲在該訂單。

11

添加到其他優秀的職位。

有時你不想指定參數的數量想要爲它們使用鍵(如果方法中沒有使用字典中傳遞的一個參數,編譯器會報錯)。

def manyArgs1(args): 
    print args.a, args.b #note args.c is not used here 

def manyArgs2(args): 
    print args.C#note args.b and .c are not used here 

class Args: pass 

args = Args() 
args.a = 1 
args.b = 2 
args.c = 3 

manyArgs1(args) #outputs 1 2 
manyArgs2(args) #outputs 3 

然後,你可以做這樣的事情

myfuns = [manyArgs1, manyArgs2] 
for fun in myfuns: 
    fun(args) 
1
def f(dic): 
    if 'a' in dic: 
     print dic['a'], 
     pass 
    else: print 'None', 

    if 'b' in dic: 
     print dic['b'], 
     pass 
    else: print 'None', 

    if 'c' in dic: 
     print dic['c'], 
     pass 
    else: print 'None', 
    print 
    pass 
f({}) 
f({'a':20, 
    'c':30}) 
f({'a':20, 
    'c':30, 
    'b':'red'}) 
____________ 

上面的代碼將輸出

None None None 
20 None 30 
20 red 30 

這是一個用字典的方式傳遞變量參數一樣好

7

如果可以的話,Skurmedel的c頌歌是爲蟒蛇2;使其適應python 3,將iteritems更改爲items並將括號添加到print。這可能會阻止像我這樣的初學者碰到: AttributeError: 'dict' object has no attribute 'iteritems'和在其他地方搜索(例如Error 「 'dict' object has no attribute 'iteritems' 」 when trying to use NetworkX's write_shp())爲什麼會發生這種情況。

def myfunc(**kwargs): 
for k,v in kwargs.items(): 
    print("%s = %s" % (k, v)) 

myfunc(abc=123, efh=456) 
# abc = 123 
# efh = 456 

和:

def myfunc2(*args, **kwargs): 
    for a in args: 
     print(a) 
    for k,v in kwargs.items(): 
     print("%s = %s" % (k, v)) 

myfunc2(1, 2, 3, banan=123) 
# 1 
# 2 
# 3 
# banan = 123 
相關問題