什么时候在 Python 中使用弱引用? [英] When to use weak references in Python?

查看:50
本文介绍了什么时候在 Python 中使用弱引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释一下弱引用的用法?

Can anyone explain usage of weak references?

文档 没有准确解释它,它只是说 GC 可以随时销毁通过弱引用链接的对象.那么拥有一个可以随时消失的物体有什么意义呢?如果我需要在它消失后立即使用它怎么办?

The documentation doesn't explain it precisely, it just says that the GC can destroy the object linked to via a weak reference at any time. Then what's the point of having an object that can disappear at any time? What if I need to use it right after it disappeared?

你能用一些很好的例子来解释它们吗?

Can you please explain them with some good examples?

谢谢

推荐答案

弱引用的典型用途是如果 A 引用 B 并且 B 引用 A.如果没有适当的循环检测垃圾收集器,这两个即使没有来自外部"的引用,对象也永远不会被垃圾回收.但是,如果其中一个引用是弱"的,对象将被正确地 GC.

The typical use for weak references is if A has a reference to B and B has a reference to A. Without a proper cycle-detecting garbage collector, those two objects would never get GC'd even if there are no references to either from the "outside". However if one of the references is "weak", the objects will get properly GC'd.

然而,Python 确实有一个循环检测垃圾收集器(从 2.0 开始!),所以这不算数:)

However, Python does have a cycle-detecting garbage collector (since 2.0!), so that doesn't count :)

弱引用的另一个用途是缓存.weakref 文档中提到:

Another use for weak references is for caches. It's mentioned in the weakref documentation:

弱引用的主要用途是实现保存大对象的缓存或映射,在这种情况下,希望大对象不会仅仅因为它出现在缓存或映射中而保持活动状态.

A primary use for weak references is to implement caches or mappings holding large objects, where it’s desired that a large object not be kept alive solely because it appears in a cache or mapping.

如果 GC 决定销毁这些对象之一,而您需要它,您只需重新计算/重新获取数据即可.

If the GC decides to destroy one of those objects, and you need it, you can just recalculate / refetch the data.

这篇关于什么时候在 Python 中使用弱引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆