我了解 Python 不保证程序结束时对象的销毁顺序,甚至不保证它会发生。
所以我明白一个类的析构函数不能依赖全局变量,包括其他模块。
但我会认为类的对象必须在类被销毁之前被销毁。显然不是:
class A(object):
count = 0
def __init__(self):
A.count += 1
print 'Creating object, there are now', A.count
def __del__(self):
A.count -= 1
print 'Destroying object, there are now', A.count
a1 = A()
a2 = A()
在 Windows 7 x64 Python v2.7.3 上,我得到:
Creating object, there are now 1
Creating object, there are now 2
Exception AttributeError: "'NoneType' object has no attribute 'count'" in <bound
method A.__del__ of <__main__.A object at 0x0234B8B0>> ignored
Exception AttributeError: "'NoneType' object has no attribute 'count'" in <bound
method A.__del__ of <__main__.A object at 0x0234BE90>> ignored
我了解如何正确清理 Python 对象的含义?. 但这种情况适用于类(我的 C++ 朋友的共享或“静态”)变量。实例肯定有对类变量的引用,它不应该首先被销毁,因为我们仍然有对它的引用?
在该类的对象之前销毁该类是问题还是错误?也许我的问题是“类共享变量实际存储在哪里?”
(是的,我知道这可以使用上下文管理器来纠正,甚至简单地:
del a1
del a2
在类被销毁之前销毁对象。)