How do you create a weak reference to an object in Python?
如何在Python中创建对象的弱引用?
1 个解决方案
#1
11
>>> 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())
See the wearkref module docs for more details. You can also use weakref.proxy
to create an object that proxies o. Will throw ReferenceError
if used when the referent is no longer referenced.
有关更多详细信息,请参阅wearkref模块文档。您还可以使用weakref.proxy来创建代理o的对象。如果在不再引用引用对象时使用,则抛出ReferenceError。
#1
11
>>> 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())
See the wearkref module docs for more details. You can also use weakref.proxy
to create an object that proxies o. Will throw ReferenceError
if used when the referent is no longer referenced.
有关更多详细信息,请参阅wearkref模块文档。您还可以使用weakref.proxy来创建代理o的对象。如果在不再引用引用对象时使用,则抛出ReferenceError。