问题描述
今天早些时候我问了这个关于__del__()
使用导入模块的对象的方法.问题是 __del__()
想要使用模块 os
,但有时(并非总是)该模块已经被删除.有人告诉我,当 Python 程序终止时,删除对象和模块的顺序可以是随机的,并且是未定义的.但是,对于我的应用程序,我确实需要确保在删除模块(在其中实例化对象)之前删除对象(我创建的类的实例).有没有办法做到这一点?
Earlier today I asked this question about the __del__()
method of an object which uses an imported module. The problem was that __del__()
wants to make use of the module os
, but sometimes (not always) the module has already been deleted. I was told that when a Python program terminates, the order in which objects and modules are deleted can be random, and is undefined. However, for my application, I really need to make sure that an object (instance of a class I created) gets deleted before the module (in which the object is instantiated) gets deleted. Is there a way of doing this?
推荐答案
正如我们之前告诉你的,你真的不应该依赖 __del__
在解释器退出时被调用.正确执行此操作有两种选择:
As we told you before, you really shouldn't rely on __del__
being called when the interpreter exits. There are two options for doing this properly:
第一个是aexit
import os
import atexit
class Logger(object):
def on_exit(self):
print "os: %s." % os
logger = Logger()
atexit.register(logger.on_exit)
这可确保您的记录器在退出时完成.
This makes sure that your logger gets finalized at exit.
*多读一点你的问题,因为你计划将单个实例绑定到一个定义实例类的模块,下面的上下文管理器解决方案将不起作用,因为没有办法留在上下文中用于整个程序的执行.您需要使用 atexit.register
.然而,从程序设计的角度来看,如果重构代码允许的话,我更愿意使用上下文管理器来管理我的资源而不是 atexit.register
.
*Reading a little more into your problem, since you plan on having a single instance bound to a module which defines the instances's class, the context manager solution below won't work for this since there's no way to stay in the context for the entire execution of your program. You'll need to use atexit.register
. However, from the standpoint of program design, I would much prefer to use a context manager to manage my resources than atexit.register
if restructuring the code would allow it.
第二种方法是让你的类成为上下文管理器,它在您退出上下文时执行清理代码.然后你的代码看起来像:
The second way to do it is make your class a context manager which executes the cleanup code when you exit the context. Then your code would look like:
import os
class Logger(object):
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
print "os:",str(os)
with Logger() as logger:
#do something ...
这篇关于Python如何确保在模块死亡之前调用对象的__del__()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!