python - 为什么 class.__weakref__ 不是 None,而 instance.__weakref__ 是 None?

标签 python weak-references python-internals

__weakref__ 与弱引用有关。我了解弱引用背后的整个想法以及我可能在哪里使用它们。我唯一没有得到的描述如下:

一个实例本身没有 __weakref__ 属性,与类不同,因此实例继承 __weakref__ 来自类,this意味着 A.__weakref__ 应该与 A().__weakref__ 相同:

>>> class A: pass
...
>>> A().__dict__            # Each instance starts out as an empty namespace 
{}
>>> A.__weakref__ is None; 
False
>>> A().__weakref__ is None   #But this is True!
True 

为什么 A.__weakref__ 不是 Noneinstance.__weakref__None 尽管实例继承 __weakref__ 来自类(class)?

最佳答案

一个类有一个__weakref__ data descriptor attribute ;这就像一个属性;只有当您访问实例上的属性时,它才会自动绑定(bind)。弱引用的实际数据存储在 C 结构中,这是 Python 用来表示内存中的类和实例的数据结构的一部分。

因此,实例不需要它们自己的 __weakref__ 属性。类描述符绑定(bind)到实例数据结构,然后 C 代码只查找正确的 C 结构以检索所需的信息。

访问类的属性,生成描述符对象本身。这不是 None;它是描述符对象。在一个实例上,绑定(bind)属性产生弱引用。没有弱引用意味着 None 被返回。

您可以通过 A.__dict__['__weakref__'] 访问对象来重新创建描述符行为(绕过正常的 type.__getattribute__() 绑定(bind)行为), 然后直接调用 __get__:

>>> import weakref
>>> class A(object): pass
...
>>> a = A()
>>> A.__weakref__
<attribute '__weakref__' of 'A' objects>
>>> descriptor = A.__dict__['__weakref__']
>>> descriptor.__get__(None, A)
<attribute '__weakref__' of 'A' objects>
>>> a = A()
>>> a.__weakref__ is None
True
>>> descriptor.__get__(a) is None
True
>>> wr = weakref.ref(a)  # add a weak reference
>>> wr
<weakref at 0x10bd86d68; to 'A' at 0x10bad3588>
>>> a.__weakref__
<weakref at 0x10bd86d68; to 'A' at 0x10bad3588>
>>> descriptor.__get__(a)
<weakref at 0x10bd86d68; to 'A' at 0x10bad3588>

关于python - 为什么 class.__weakref__ 不是 None,而 instance.__weakref__ 是 None?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36828606/

相关文章:

python - 文本小部件不显示 Unicode 字符

python - python 中的派系

python - 为什么类的主体在定义时执行?

javascript - 如何设置变量的默认值?

python - Seaborn - 从 DataFrame 直方图中删除间距

objective-c - TableView :cellForRowAtIndexPath: not called because array is empty?

scala - WeakReference 和 Scala REPL

c# - ConditionalWeakTable<TKey, TValue> 是否应该用于非编译器目的?

python - 如何在Python中获取函数的实际参数名称?

Python 字符串文字连接