可以将可变数量的参数传递给函数吗?

时间:2009-05-28 07:50:10

标签: python

与在C或C ++中使用varargs类似:

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

6 个答案:

答案 0 :(得分:396)

这很简单,如果忽略关键字参数,则有效:

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中所示。

答案 1 :(得分:209)

添加以展开帖子:

您也可以发送多个键值参数。

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

它们必须按顺序声明和调用,即函数签名需要是* args,** kwargs,并按此顺序调用。

答案 2 :(得分:16)

如果可以的话,Skurmedel的代码是针对python 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

答案 3 :(得分:12)

添加其他优秀帖子。

有时你不想指定的参数个数想要为它们使用键(如果在方法中没有使用字典中传递的一个参数,编译器会抱怨)。 / p>

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)

答案 4 :(得分:2)

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

这与通过字典

传递变量参数一样好

答案 5 :(得分:1)

除了已经提到的不错的答案之外,另一种解决方法还取决于您可以按位置传递可选的命名参数。例如,

def f(x,y=None):
    print(x)
    if y is not None:
        print(y)

收益

In [11]: f(1,2)
1
2

In [12]: f(1)
1
相关问题