我正在使用对象的 __del__()
取消订阅事件(使用类似于 this 的事件方案):
import my_enviroment
class MyClass():
def __del__(self):
my_environment.events.my_event -= self.event_handler_func
奇怪的是,我在程序运行结束时收到以下错误:
Exception AttributeError: "'NoneType' object has no attribute 'events'" in <bound method MyClass.__del__ of <myclass.MyClass instance at 0x04C54580>> ignored
这怎么可能?! my_environment
是我导入的模块,怎么会是None呢? (events
是一个全局对象,里面有my_event
等事件钩子(Hook))
最佳答案
[...] other globals referenced by the
__del__()
method may already have been deleted or in the process of being torn down (e.g. the import machinery shutting down). For this reason,__del__()
methods should do the absolute minimum needed to maintain external invariants.
换句话说,当你的对象调用__del__
方法时,my_enviroment
可能已经被python“删除”了,所以它可以是None...
关于python - 无法在 __del__() 中引用导入的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8590238/