有没有一种方法可以在类外部自初始化函数?

时间:2019-05-14 15:58:17

标签: python initialization

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

[failed features:
src.test.features.envtest.env-create: [1.1:13] env-create.feature:9 - path: $, actual: '', expected: '{"id":"#string","name":"tests","gcpProjectName":"D-COO-ContinuousCollaboration","url":"https://fake.com"}', reason: not a sub-string

我想知道是否有比定义函数然后再调用它更麻烦的自动调用函数的方法。

我试图将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__

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

谢谢。

为澄清而编辑

1 个答案:

答案 0 :(得分:0)

如果您在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