Python 中的 __weakref__ 到底是什么? [英] What exactly is __weakref__ in Python?

查看:73
本文介绍了Python 中的 __weakref__ 到底是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

令人惊讶的是,没有关于 __weakref__ 的明确文档.此处解释了弱引用.__weakref____slots__ 的文档中也有简短的提及.但是我找不到关于 __weakref__ 本身的任何信息.

Surprisingly, there's no explicit documentation for __weakref__. Weak references are explained here. __weakref__ is also shortly mentioned in the documentation of __slots__. But I could not find anything about __weakref__ itself.

__weakref__ 究竟是什么?- 它只是一个充当标志的成员:如果存在,该对象可能是弱引用的吗?- 或者它是一个可以被覆盖/分配以获得所需行为的函数/变量?怎么样?

What exactly is __weakref__? - Is it just a member acting as a flag: If present, the object may be weakly-referenced? - Or is it a function/variable that can be overridden/assigned to get a desired behavior? How?

推荐答案

__weakref__ 只是一个引用当前对象的所有弱引用的不透明对象.实际上,它是 weakref (或有时 weakproxy),它既是对象的弱引用,又是该对象所有弱引用的双向链表的一部分.

__weakref__ is just an opaque object that references all the weak references to the current object. In actual fact it's an instance of weakref (or sometimes weakproxy) which is both a weak reference to the object and part of a doubly linked list to all weak references for that object.

这只是一个实现细节,它允许垃圾收集器通知弱引用其所指对象已被收集,并且不再允许访问其底层指针.

It's just an implementation detail that allows the garbage collector to inform weak references that its referent has been collected, and to not allow access to its underlying pointer anymore.

弱引用不能依赖于检查它所引用的对象的引用计数.这是因为该内存可能已被回收,现在正被另一个对象使用.最好的情况是 VM 会崩溃,最坏的情况是弱引用将允许访问它最初没有引用的对象.这就是垃圾收集器必须通知弱引用其所指对象不再有效的原因.

The weak reference can't rely on checking the reference count of the object it refers to. This is because that memory may have been reclaimed and is now being used by another object. Best case scenario the VM will crash, worst case the weak reference will allow access to an object it wasn't originally referring to. This is why the garbage collector must inform the weak reference its referent is no longer valid.

结构和 C 参见 weakrefobject.h-此对象的API.实现细节在这里

See weakrefobject.h for the structure and C-API for this object. And the implementation detail is here

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

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