![](/img/trans.png)
[英]Why does Python seem to treat instance variables as shared between objects?
[英]Why does Python destroy class variables before objects?
我知道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
在类被销毁之前销毁对象。)
也许我的问题是“实际存储了类共享变量的位置?”
如果这是你的问题,那么答案是“在课堂上”。
解决你的大问题:正如你所指出的, __del__
不能依赖全局变量 - 但A
是一个全局变量,所以你不能依赖它。 有趣的是,我无法在文档中找到关于此的正式声明,但是在互联网上有各种各样的参考,即__del__
不能使用全局变量。 这是一个:
当Python程序终止时,每个模块中的全局变量都设置为None。 发生这种情况的顺序是未定义的
如果您通过self.__class__.count
而不是A.count
访问self.__class__.count
, A.count
。 (这也是使用self.count
时它的工作原理。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.