2009-05-28 261 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 
相关问题