Domanda

Come si crea un riferimento debole a un oggetto in Python?

È stato utile?

Soluzione

>>> 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()) 

Vedi il documenti del modulo wearkref per ulteriori dettagli.Puoi anche usare weakref.proxy per creare un oggetto che proxy o.Lancerà ReferenceError se utilizzato quando il referente non è più referenziato.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top