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

说:

def myfunc(anotherfunc, extraArgs):
    # run anotherfunc and also pass the values from extraArgs to it
    pass

所以这基本上是两个问题:
  • 可以吗?
  • 如果是的话,如何在其他函数中使用该函数?我需要使用exec(),eval()还是类似的东西?从来不需要与他们搞混。

  • 顺便说一句,extraArgs是anotherfunc参数的列表/元组。

    最佳答案



    是的。

    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
    >>>
    

    10-05 20:49
    查看更多