简体   繁体   English

可以将可变数量的 arguments 传递给 function 吗?

[英]Can a variable number of arguments be passed to a function?

In a similar way to using varargs in C or C++:以类似于在 C 或 C++ 中使用可变参数的方式:

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

Yes.是的。 You can use *args as a non-keyword argument.您可以使用*args作为非关键字参数。 You will then be able to pass any number of arguments.然后,您将能够传递任意数量的参数。

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)

As you can see, Python will unpack the arguments as a single tuple with all the arguments.如您所见,Python 会将参数解包为包含所有参数的单个元组。

For keyword arguments you need to accept those as a separate actual argument, as shown in Skurmedel's answer .对于关键字参数,您需要将它们作为单独的实际参数接受,如Skurmedel 的回答所示。

Adding to unwinds post:添加到放松帖子:

You can send multiple key-value args too.您也可以发送多个键值参数。

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

And you can mix the two:你可以混合两者:

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

They must be both declared and called in that order, that is the function signature needs to be *args, **kwargs, and called in that order.它们必须按顺序声明和调用,即函数签名需要是 *args、**kwargs 并按该顺序调用。

If I may, Skurmedel's code is for python 2;如果可以的话,Skurmedel 的代码适用于 python 2; to adapt it to python 3, change iteritems to items and add parenthesis to print .使其适应 python 3,将iteritems更改为items并将括号添加到print That could prevent beginners like me to bump into: AttributeError: 'dict' object has no attribute 'iteritems' and search elsewhere (eg Error “ 'dict' object has no attribute 'iteritems' ” when trying to use NetworkX's write_shp() ) why this is happening.这可以防止像我这样的初学者碰到: AttributeError: 'dict' object has no attribute 'iteritems'并在其他地方搜索(例如,当尝试使用 NetworkX 的 write_shp() 时,错误“'dict' object has no attribute 'iteritems'” )为什么这正在发生。

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

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

and:和:

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

Adding to the other excellent posts.添加到其他优秀职位。

Sometimes you don't want to specify the number of arguments and want to use keys for them (the compiler will complain if one argument passed in a dictionary is not used in the method).有时你不想指定的参数的数量要使用它们键(如果在字典中传递的一个参数的方法不使用编译器会抱怨)。

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

Then you can do things like然后你可以做这样的事情

myfuns = [manyArgs1, manyArgs2]
for fun in myfuns:
  fun(args)
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'})
____________

the above code will output上面的代码会输出

None None None
20 None 30
20 red 30

This is as good as passing variable arguments by means of a dictionary这与通过字典传递变量参数一样好

Another way to go about it, besides the nice answers already mentioned, depends upon the fact that you can pass optional named arguments by position.除了已经提到的好答案之外,另一种解决方法取决于您可以按位置传递可选命名参数的事实。 For example,例如,

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

Yields产量

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

In [12]: f(1)
1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM