我需要抢占__del__,我想知道怎样做才是正确的。基本上我在代码中的问题是这样的..
class A:
def __init__(self):
self.log = logging.getLogger()
self.log.debug("In init")
self.closed = False
def close(self):
self.log.debug("Doing some magic")
self.closed = True
def __del__(self):
if not self.closed:
self.close()
self.log.debug("In closing")
# What should go here to properly do GC??现在有没有办法调用标准的GC特性?
感谢阅读!!
史蒂夫
发布于 2009-10-15 22:56:30
__del__不是一个真正的析构函数。它在对象被销毁之前被调用,以释放它所持有的任何资源。它不需要担心释放内存本身。
如果您继承的类也可能具有开放资源,那么您也可以随时调用父类的__del__。
发布于 2009-10-15 23:10:11
为此,请使用with语句。
请参阅http://docs.python.org/reference/compound_stmts.html#the-with-statement
with语句保证,如果
()方法返回时没有错误,则将始终调用exit()。
使用上下文管理器对象的__exit__,而不是胡乱使用__del__。
发布于 2009-10-15 22:59:38
如果您希望手动调用GC,那么可以调用gc.collect()。
https://stackoverflow.com/questions/1575567
复制相似问题