import weakref
class Cheese:
def __init__(self,kind):
self.kind = kind
def __repr__(self):
return "cheese {}".format(self.kind)
stock = weakref.WeakValueDictionary()
catalog = [Cheese("red"),Cheese("block"),Cheese("lock"),Cheese("hehe")]
for cheese in catalog:
stock[cheese.kind] = cheese
print(sorted(stock.keys()))
del catalog
print(sorted(stock.keys()))
结果是:
['block', 'hehe', 'lock', 'red']
['hehe']
问题:为什么结果不是:
['block', 'hehe', 'lock', 'red']
['block', 'hehe', 'lock', 'red']
最佳答案
那是因为您正在为 stock
使用 weakref.WeakValueDictionary()
。来自docs :
A weak reference to an object is not enough to keep the object alive: when the only remaining references to a referent are weak references, garbage collection is free to destroy the referent and reuse its memory for something else.
因此销毁 catalog
允许垃圾收集器销毁 stock
内容。
只有剩余元素是最后一个元素,因为它被最后一个循环项引用为 cheese
如果您执行 del cheese
,则第二个打印输出完全是空的。
关于python - <<Fluent python>> P372 例题8-19 为什么只存在最后一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54436110/