python - <<Fluent python>> P372 例题8-19 为什么只存在最后一个元素?

标签 python

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/

相关文章:

python - 将 python 日志记录格式应用于包含新行的消息的每一行

Python 使用子数组动态构建 JSON

python - 时间复杂度最小数组数量

python - 如何删除斜线后的空格 "/"

python - 更改 django-haystack 中的默认 View

python - 将 QHBoxLayout 的每个小部件对齐到顶部

python - 正则表达式在 Pythex 上运行良好,但在 Python 上运行不佳

python - 有没有办法在代码中使用 np.array

python - A* 搜索迷宫 - 当路径不存在时无限循环 - Python

c# - 使用 Bouncy CaSTLe 在 C# 中加密和使用 AES(EAX 模式)在 Python 中解密的问题