Pergunta

Como você cria uma referência fraca para um objeto em Python?

Foi útil?

Solução

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

Veja o documentos do módulo wearkref para mais detalhes.Você também pode usar weakref.proxy para criar um objeto que faça proxy o.Vai jogar ReferenceError se usado quando o referente não é mais referenciado.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top