可以将可变数量的参数传递给函数吗? [英] Can a variable number of arguments be passed to a function?

查看:46
本文介绍了可以将可变数量的参数传递给函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似于在 C 或 C++ 中使用可变参数:

In a similar way to using varargs in C or C++:

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

推荐答案

是的.您可以使用 *args 作为 非关键字 参数.然后,您将能够传递任意数量的参数.

Yes. You can use *args as a non-keyword argument. 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)

如您所见,Python 会将参数解包为包含所有参数的单个元组.

As you can see, Python will unpack the arguments as a single tuple with all the arguments.

对于关键字参数,您需要将它们作为单独的实际参数接受,如Skurmedel 的回答所示.

For keyword arguments you need to accept those as a separate actual argument, as shown in Skurmedel's answer.

这篇关于可以将可变数量的参数传递给函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆