Python3传递内部帮助函数的参数

时间:2014-12-26 15:22:27

标签: python python-3.x

除了在bar之外移动辅助函数或传入FUNC_TO_CALL的字符串然后根据字符串选择函数之外,我有没有其他方法可以执行以下操作?

#foo.py
def bar(FUNC_TO_CALL)
   def helper_function_1():
       ...
   def helper_function_2():
       ...

   FUNC_TO_CALL()

#main.py
foo.bar(bar.helper_function_1) #<- HOW DO I PASS IN THIS HELPER INTERNAL TO BAR AS ARGUMENT?

我有一个函数bar,其中包含许多帮助器,我希望通过传递给bar的参数来调用它们。另一种方法是将所有帮助程序移动到模块级别,但这很麻烦,因为它们在bar之外是无用的。

1 个答案:

答案 0 :(得分:1)

你可能想研究用bar制作装饰的可能性:

def bar(helper):
    def process():
        print('preprocessing...')
        # Anything you need to do prior to calling the helper function
        helper()

    return process

@bar
def helper_function_1():
    print('helper 1')

@bar
def helper_function_2():
    print('helper 2')

if __name__ == '__main__':
    helper_function_1()
    helper_function_2()

这给出了输出:

preprocessing...
helper 1
preprocessing...
helper 2

虽然辅助函数只是bar工作的一小部分,但它没有多大意义。