如果您了解所有这些内容,为什么不以Pythonic的方式来做呢?比较另一个需要清除的类:
tempfile.TemporaryDirectory。
with TemporaryDirectory() as tmp: # ...# tmp is deleteddef foo(): tmp = TemporaryDirectory()foo()# tmp is deleted
他们如何做到这一点?这是相关的位:
import weakrefclass Foo(): def __init__(self, name): self.name = name self._finalizer = weakref.finalize(self, self._cleanup, self.name) print("%s reporting for duty!" % name) @classmethod def _cleanup(cls, name): print("%s feels forgotten! Bye!" % name) def cleanup(self): if self._finalizer.detach(): print("%s told to go away! Bye!" % self.name)def foo(): print("Calling Arnold") tmpfoo = Foo("Arnold") print("Finishing with Arnold")foo()# => Calling Arnold# => Arnold reporting for duty# => Finishing with Arnold# => Arnold feels forgotten. Bye!def bar(): print("Calling Rocky") tmpbar = Foo("Rocky") tmpbar.cleanup() print("Finishing with Rocky")bar()# => Calling Rocky# => Rocky reporting for duty!# => Rocky told to go away! Bye!# => Finishing with Rockyweakref.finalize将
_cleanup在对象被垃圾回收时触发,或者在程序结束时(如果它仍在周围)触发。我们可以保留finalizer,以便可以明确杀死对象(使用
detach)并将其标记为死对象,以便不调用finalizer(当我们要手动处理清理操作时)。
如果您想使用来支持上下文用法
with,那么添加
__enter__和
__exit__方法是很简单的,只需调用
cleanupin
__exit__(如上所述的“手动清理”)即可。



