在试图删除对象的最后引用时,我遇到了一个奇怪的问题。
守则是:
import sys
import weakref
class Ref:
def __init__(self, name):
self.name = name
self.ref = []
def reference(self, obj):
name = obj.name
self.ref.append(
weakref.ref(obj, lambda wref: print('{!r} is dead.'.format(name))))
a = Ref('a')
b = Ref('b')
c = Ref('c')
d = Ref('d')
a.reference(b)
b.reference(c)
c.reference(d)
d.reference(a)
print('reference count before killed:', sys.getrefcount(d.ref[0]()))
del a
print('reference count after killed:', sys.getrefcount(d.ref[0]()))输出如下:
reference count before killed: 2
'a' is dead.
reference count after killed: 1547
'd' is dead.
'c' is dead.但有时(完全是随机的)我只收到了'd' is dead.或'c' is dead. (但从来没有收到'b' is dead.),或者完全没有这些消息。
所以我的第一个问题是:这个奇怪的参考计数1547是什么?它是从哪里来的?
第二个问题是:为什么杀死实例a创建这个随机的“杀死其他实例”效应?
发布于 2013-09-17 01:20:16
在a被GC化之后,d.ref[0]()会生成None。这就是为什么在删除a之后,你得到了1547的重新计数;毕竟,你不能要求一个收集的物体的重新计数,对吗?
删除c和d的奇怪之处在于,它不能保证解释器退出时对象是否还活着,将经历正常的销毁过程。b、c和d在脚本的末尾都是活动的。有时,他们会得到GC正常,弱的回调将运行。有时候,这是不可能的。Python在这里不做任何承诺。
https://stackoverflow.com/questions/18839727
复制相似问题