python - 在python中调用带有参数列表的函数

我试图在 python 的另一个函数中调用一个函数,但找不到正确的语法。我想做的是这样的:

def wrapper(func, args):
    func(args)

def func1(x):
    print(x)

def func2(x, y, z):
    return x+y+z

wrapper(func1, [x])
wrapper(func2, [x, y, z])

在这种情况下,第一次调用会起作用,第二次不会。 我要修改的是包装函数,而不是调用函数。

最佳答案

稍微扩展其他答案:

行内:

def wrapper(func, *args):

args 旁边的 * 表示“获取给定的其余参数并将它们放入名为 args 的列表中”。

行内:

    func(*args)

这里 args 旁边的 * 表示“将这个名为 args 的列表‘解包’到其余参数中。

因此您可以执行以下操作:

def wrapper1(func, *args): # with star
    func(*args)

def wrapper2(func, args): # without star
    func(*args)

def func2(x, y, z):
    print x+y+z

wrapper1(func2, 1, 2, 3)
wrapper2(func2, [1, 2, 3])

wrapper2 中,列表是显式传递的,但在两个包装器 args 中都包含列表 [1,2,3]

https://stackoverflow.com/questions/817087/

相关文章:

linux - 如何在 Linux 上的某个时间运行脚本?

python - 了解python的主要方法

c - 如何在 C 中使用/dev/random 或 urandom?

linux - 如何连接两个字符串以构建完整路径

python - 为什么字典和集合中的顺序是任意的?

python - Jinja2 简写条件

Python 风格 - 用字符串续行?

python - 如何查看安装了哪个版本的nltk、scikit learn?

python - 在 localhost 上,我如何选择一个空闲端口号?

python - 更新不同深度的嵌套字典的值