为什么Python会在对象之前销毁类变量?
我知道Python不能保证在程序结束时销毁对象的顺序,甚至不能保证它会发生 所以我知道类的析构函数不能依赖全局变量,包括其他模块 但是我认为类的对象必须在类被销毁之前被销毁。显然不是:为什么Python会在对象之前销毁类变量?,python,class,scope,destructor,Python,Class,Scope,Destructor,我知道Python不能保证在程序结束时销毁对象的顺序,甚至不能保证它会发生 所以我知道类的析构函数不能依赖全局变量,包括其他模块 但是我认为类的对象必须在类被销毁之前被销毁。显然不是: class A(object): count = 0 def __init__(self): A.count += 1 print 'Creating object, there are now', A.count def __del__(self):
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
在销毁类之前销毁对象。)
也许我的问题是‘类共享变量实际存储在哪里?’
如果这是你的问题,答案是“在课堂上”
为了回答你更大的问题:正如你所指出的,\uuu del\uuu
不能依赖全局变量,但是A
是一个全局变量,所以你不能依赖它。有趣的是,我在文档中找不到关于这一点的官方声明,但互联网上有各种各样的参考文献表明\uu del\uu
不能使用全局变量变量。是一个:
当Python程序终止时,每个模块中的全局变量都设置为“无”。这种情况发生的顺序未定义
如果您通过
self.\uuu class\uuuu.count
而不是A.count
访问计数,则该功能将起作用(这也是使用self.count
时该功能起作用的原因)关于实例的。\uuuuu class\uuuuuuu
呢?@FatalError:你说得对,引用的问题是一个令人费解的问题。问题不是类本身已经被删除,而是引用它的全局变量已经设置为“无”。我编辑了我的答案。奇怪的是,当我尝试使用。\uuuuuu class\uuuuuuuucode>。it app时,我得到了同样的行为在这种情况下,在调用\uu del\uuuu
之前,耳朵好像也被设置为None
,这有点令人惊讶。@FatalError:您是否将-=
和print
都更改为使用self.\uu class\uuuu
?我以为我也看到了您看到的内容,但我仍在使用环境进行print A.count
ent设置PYTHONVERBOSE=2
您可以看到模块清理和属性清理的顺序。
del a1
del a2