在Python中,如何将函数(回调)作为参数传递给另一个函数?

140 投票
11 回答
256424 浏览
提问于 2025-04-16 19:14

假设我有一些代码如下:

def myfunc(anotherfunc, extraArgs):
    # somehow call `anotherfunc` here, passing it the `extraArgs`
    pass

我想把另一个已经存在的函数作为 anotherfunc 的参数传进去,同时把一组参数(可以是列表或元组)作为 extraArgs 传入,然后让 myfunc 用这些参数来调用传进来的函数。

这样做可以吗?我该怎么做呢?

11 个回答

19

在Python中,函数被视为一等公民。这意味着函数可以像其他数据一样被使用和操作。不过,函数的定义应该稍微有些不同

def myfunc(anotherfunc, extraArgs, extraKwArgs):
    return anotherfunc(*extraArgs, **extraKwArgs)
37

这里有另一种方法,使用了 *args(可选的还有 **kwargs):

def a(x, y):
    print(x, y)

def b(other, function, *args, **kwargs):
    function(*args, **kwargs)
    print(other)

b('world', a, 'hello', 'dude')

输出结果

hello dude
world

注意,function*args**kwargs 必须按照这个顺序出现,并且必须是调用 function 的函数(b)的最后几个参数。

157

是的,这是可能的。myfunc可以像下面这样调用传入的函数:

def myfunc(anotherfunc, extraArgs):
    anotherfunc(*extraArgs)

这里有一个完整的示例:

>>> def x(a, b):
...     print('a:', a, 'b:', b)
... 
>>> def y(z, t):
...     z(*t)
... 
>>> y(x, ('hello', 'manuel'))
a: hello b: manuel

撰写回答