有没有办法在 class 之外自初始化一个函数?

It there a way to self-initialise a function outside of a class?

我有这段代码需要 运行 每次执行程序(它会清空一个文件夹):

import os

def ClearOutputFolder():
    ''' Clear 'Output/' directory '''
    for file in os.listdir('Output'):
        file_path = os.path.join('Output', file)
        try:
            if os.path.isfile(file_path):
                os.unlink(file_path)
        except Exception as e:
            print(e)

ClearOutputFolder()

我想知道是否有比定义函数然后稍后调用更简单的自动调用函数的方法。

我试图将 __init__ 放在 class 之外,只是为了看看,但正如预期的那样,它的行为就像一个正常的函数,需要被调用。

import os

def __init__():
    delete_stuff                # this runs but does nothing on its own

这不是生死攸关的问题,显然,我只是好奇是否有一个我不知道的简单解决方案。

谢谢。

编辑澄清

如果您在 if __name__ == '__main__ 块中调用函数,它将在启动程序包时自动执行。

import os

def ClearOutputFolder():
    ''' Clear 'Output/' directory '''
    for file in os.listdir('Output'):
        file_path = os.path.join('Output', file)
        try:
            if os.path.isfile(file_path):
                os.unlink(file_path)
        except Exception as e:
            print(e)

def main():
    ClearOutputFolder()


if __name__ == '__main__':

    main()

如果您希望在导入时调用,您可以这样做:

import os

def ClearOutputFolder():
    ''' Clear 'Output/' directory '''
    for file in os.listdir('Output'):
        file_path = os.path.join('Output', file)
        try:
            if os.path.isfile(file_path):
                os.unlink(file_path)
        except Exception as e:
            print(e)

ClearOutputFolder()   # this call is executed upon importing the package