8 六月, 2006

pyton: The __del__ method is not a reliable cleanup mechanism

Python初学者的经典教程《A Byte of Python》,在讲述“Class and Object Variables”的时候,有一个Person Class的例子,其中包括__init__和__del__实现。

比较C++,__init__类似于constructor,而__del__类似于destructor。实际上,Python的实现机制和C++有很大区别,特别是对于__del__。

作者也在此文末尾,特地提醒到:“ The __del__ method is run when the object is no longer in use and there is no guarantee when that method will be run. If you want to explicitly do this, you just have to use the del statement which we have used in previous examples.”

意思是说,如果想保证__del__顺利执行,需要显式调用del函数。否则的话,python会在垃圾收集的时候释放这些对象占用的内存,那时候,很难保证全局域中的Class声明本身是否还可用。很有可能你会在程序退出的时候,发生类似异常“exceptions.AttributeError:"'NoneType' object has no attribute...”。"NoneType"就是因为类声明已经先于对象被释放了(be set to None)

所以说,“The __del__ method is not a reliable cleanup mechanism”。你可以通过添加另外的方法实现这部分功能,如果一定要使用__del__的话,请务必显式(explicit)调用del来释放对象。


最新回复
发表评论


















Bold Italic Link