如何在Python中创建对对象的弱引用?
时间:2020-03-05 18:49:43 来源:igfitidea点击:
如何在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
。