Python如何确保在模块死亡之前调用对象的__del __()方法? [英] Python how to ensure that __del__() method of an object is called before the module dies?

查看:74
本文介绍了Python如何确保在模块死亡之前调用对象的__del __()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天早些时候,我问了关于__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:

第一个是atexit

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.

第二种(better *)方法是使您的类成为

The second (better*) 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 __()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆