在Python中实现清理方法的理想方法

在Python中实现清理方法的理想方法,python,code-cleanup,Python,Code Cleanup,我们写这封信是想说得更清楚些,但我相信克拉克J明白了。我有一个包含以下内容的文件: class tests: def test1(self): create something1 def test2(self): create something2 . . . . def test19(self): cleanup something1 def test20(self):

我们写这封信是想说得更清楚些,但我相信克拉克J明白了。我有一个包含以下内容的文件:

class tests:

    def test1(self):
        create something1

    def test2(self):
        create something2
    .
    .
    .
    .

    def test19(self):
        cleanup something1

    def test20(self):
        cleanup something2
如果test1或test2失败,它会留下一些东西1,一些东西2。想知道在下面的样式中使用try:finally:是否可以,以便每次程序退出之前都运行test19和test20,或者是否有一种更理想的方法来实现这一点。基本上,我的目标是确保test19和test20总是在程序退出之前运行,以防其他测试失败。谢谢

class tests:

    try:

        def test1(self):
            create something1

        def test2(self):
            create something2
        .
        .
        .
        .

    finally:

        def test19(self):
            cleanup something1

        def test20(self):
            cleanup something2

我看不出你为什么不能使用try finally块

或者,您可以使用该模块。它在程序结束后运行注册函数。它是Python2和Python3中标准库的一部分

import atexit

@atexit.register   #decorator call only works for functions without args
def function_to_run_on_exit():
    print ("doing some awesome teardown and cleanup")

def exit_function_with_args(foo, bar):
    print("cleaning up {} and {}").format(foo, bar))



atexit.register(exit_function_with_args, 'my foo', 'my bar')