我知道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()
Run Code Online (Sandbox Code Playgroud)
在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 …Run Code Online (Sandbox Code Playgroud)