Python函数作为函数参数?

新手上路,请多包涵

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

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

我想将另一个现有函数作为 anotherfunc 参数传递,并将参数列表或元组作为 extraArgs 传递,并调用传递的函数 myfunc 那些论点。

这可能吗?我该怎么做 - 我需要 exec / eval 或类似的东西吗?

原文由 a7664 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 245
1 个回答

Python 函数可以作为另一个函数的参数吗?

是的。

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

更具体地说……有各种论点……

 >>> def x(a,b):
...     print "param 1 %s param 2 %s" % (a,b)
...
>>> def y(z,t):
...     z(*t)
...
>>> y(x, ("hello","manuel"))
param 1 hello param 2 manuel

原文由 Manuel Salvadores 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题