2016-04-24 54 views
2

__weakref__与弱引用有关。我得到了弱引用背后的全部想法,以及我可能在哪里使用它们。我不明白的是在下面描述的唯一的事:为什么class .__ weakref__不是None,而instance .__ weakref__是None?

一个实例没有属性__weakref__本身,从类不同,因此实例继承__weakref__从类,这意味着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__

+0

*“,这意味着'甲.__ weakref__ '和'A().__ weakref__' *“一样 - 显然不是,所以你假设*”实例从类“*继承'__weakref__'是不正确的。 'A .__ weakref__是A().__ weakref__'的计算结果为'False'。 – jonrsharpe

回答

3

A class has a __weakref__descriptor object;这就像property或一种方法一样;只有当你访问对象的属性时才会自动绑定。弱引用的实际数据存储在C结构中,这是Python用来表示内存中的类和实例的数据结构的一部分。

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

访问类的属性,产生描述符对象本身。这不是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>