为什么 class.__weakref__ 不是 None,而 instance.__weakref__ 是 None?
Why is class.__weakref__ not None, while instance.__weakref__ is None?
__weakref__
与弱引用有关。我了解弱引用背后的整个想法以及我可能在哪里使用它们。我唯一没有得到的描述如下:
实例本身不具有属性 __weakref__
,与 class 不同,因此实例 继承 __weakref__
来自class,这意味着 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__
不是 None
而 instance.__weakref__
是 None
尽管实例从 class 继承 __weakref__
?
一个class有一个__weakref__
data descriptor attribute;这就像 property
;只有当您访问实例上的属性时,它才会自动绑定。弱引用的实际数据存储在 C 结构中,部分数据结构 Python 用于表示内存中的 classes 和实例。
因此,实例不需要它们自己的 __weakref__
属性。 class 描述符绑定到实例数据结构,然后 C 代码只查找正确的 C 结构以检索所需的信息。
访问 class 上的属性会生成描述符对象本身。这不是None
;它是描述符对象。在一个实例上,绑定属性产生弱引用。没有弱引用意味着返回 None
。
您可以通过 A.__dict__['__weakref__']
访问对象(绕过正常的 type.__getattribute__()
绑定行为),然后直接调用 __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>
__weakref__
与弱引用有关。我了解弱引用背后的整个想法以及我可能在哪里使用它们。我唯一没有得到的描述如下:
实例本身不具有属性 __weakref__
,与 class 不同,因此实例 继承 __weakref__
来自class,这意味着 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__
不是 None
而 instance.__weakref__
是 None
尽管实例从 class 继承 __weakref__
?
一个class有一个__weakref__
data descriptor attribute;这就像 property
;只有当您访问实例上的属性时,它才会自动绑定。弱引用的实际数据存储在 C 结构中,部分数据结构 Python 用于表示内存中的 classes 和实例。
因此,实例不需要它们自己的 __weakref__
属性。 class 描述符绑定到实例数据结构,然后 C 代码只查找正确的 C 结构以检索所需的信息。
访问 class 上的属性会生成描述符对象本身。这不是None
;它是描述符对象。在一个实例上,绑定属性产生弱引用。没有弱引用意味着返回 None
。
您可以通过 A.__dict__['__weakref__']
访问对象(绕过正常的 type.__getattribute__()
绑定行为),然后直接调用 __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>