如何在 Python 中创建对象的弱引用?

有帮助吗?

解决方案

>>> import weakref
>>> class Object:
...     pass
...
>>> o = Object()
>>> r = weakref.ref(o)
>>> # if the reference is still active, r() will be o, otherwise None
>>> do_something_with_o(r()) 

请参阅 wearkref 模块文档 更多细节。您还可以使用 weakref.proxy 创建一个代理 o 的对象。会扔 ReferenceError 如果在不再引用所指对象时使用。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top