内部helper函数的Python3 pass参数

2024-05-08 03:22:16 发布

您现在位置:Python中文网/ 问答频道 /正文

除了将helper函数移到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之外是无用的。你知道吗


Tags: to方法函数字符串pyhelperfoomain
1条回答
网友
1楼 · 发布于 2024-05-08 03:22:16

您可能想研究用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

尽管helper函数只是bar工作的一小部分,但这并没有多大意义。你知道吗

相关问题 更多 >