Can a variable number of arguments be passed to a function?
(P)In a similar way to use varargs in C or C+:(p)字母名称
对。
这很简单,如果忽略关键字参数,则可以使用:
1 2 3 4 5 6 7 | 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的答案所示。
添加到展开日志:
您也可以发送多个键值参数。
1 2 3 4 5 6 7 8 | 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 |
你可以把这两个混合起来:
1 2 3 4 5 6 7 8 9 10 11 | 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,并按该顺序调用。
如果可以的话,skurmedel的代码是针对python 2的;为了适应python 3,将
1 2 3 4 5 6 7 | def myfunc(**kwargs): for k,v in kwargs.items(): print("%s = %s" % (k, v)) myfunc(abc=123, efh=456) # abc = 123 # efh = 456 |
还有:
1 2 3 4 5 6 7 8 9 10 11 | 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 |
加上其他优秀的职位。
有时,您不想指定参数的数目,并且想为它们使用键(如果在一个字典中传递的一个参数在方法中没有使用,编译器会抱怨)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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 |
然后你可以做像
1 2 3 | myfuns = [manyArgs1, manyArgs2] for fun in myfuns: fun(args) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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', pass f({}) f({'a':20, 'c':30}) f({'a':20, 'c':30, 'b':'red'}) ____________ |
以上代码将输出
1 2 3 | None None None 20 None 30 20 red 30 |
这就像用字典传递变量参数一样好。