编程语言
首页 > 编程语言> > python:闭包和类

python:闭包和类

作者:互联网

我需要注册一个atexit函数用于类(请参阅下面的Foo示例),遗憾的是,我没有通过方法调用直接清理的方法:其他代码,我无法控制,调用Foo.start()和Foo.end()但有时如果遇到错误则不调用Foo.end(),所以我需要自己清理.

在这种情况下,我可以对闭包使用一些建议:

class Foo:
  def cleanup(self):
     # do something here
  def start(self):
     def do_cleanup():
        self.cleanup()
     atexit.register(do_cleanup)
  def end(self):
     # cleanup is no longer necessary... how do we unregister?

>关闭是否正常工作,例如在do_cleanup中,自我绑定的值是否正确?
>如何取消注册atexit()例程?
>有更好的方法吗?

编辑:这是Python 2.6.5

解决方法:

使注册表成为全局注册表和调用其中的函数的函数,并在必要时从那里删除它们.

cleaners = set()

def _call_cleaners():
    for cleaner in list(cleaners):
        cleaner()

atexit.register(_call_cleaners)

class Foo(object):
  def cleanup(self):
     if self.cleaned:
         raise RuntimeError("ALREADY CLEANED")
     self.cleaned = True
  def start(self):
     self.cleaned = False
     cleaners.add(self.cleanup)
  def end(self):
     self.cleanup()
     cleaners.remove(self.cleanup)

标签:python,class,atexit
来源: https://codeday.me/bug/20190721/1496935.html