在 Python 中如何使用函数(回调)作为另一个函数的参数?

2024-01-13

假设我有一些代码,例如:

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

我想传递另一个现有函数作为anotherfunc参数,以及参数列表或元组作为extraArgs,并且有myfunc使用这些参数调用传入的函数。

这可能吗?我该怎么做?


是的,这是可能的。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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Python 中如何使用函数(回调)作为另一个函数的参数? 的相关文章

随机推荐