>>> from weakref import WeakValueDictionary
>>> class Foo(object):
... pass
>>> foo = Foo()
>>> db = WeakValueDictionary()
>>> db['foo-id'] = foo
>>> del foo
>>> dict(db)
{'foo-id': <__main__.Foo object at 0x4dd946c>}
为什么它显示这个而不是空字典?请注意,此代码会产生我期望的结果:
>>> db2 = WeakValueDictionary()
>>> db2['disposable-id'] = Foo()
>>> dict(db2)
{}
在执行脚本(而不是交互式解释器)时,它的行为也符合预期:
from weakref import WeakValueDictionary
class Foo(object):
pass
foo = Foo()
db = WeakValueDictionary()
db['foo-id'] = foo
del foo
print str(dict(foo))
# prints {}