什么是weakrefoffset?

2024-10-04 11:21:59 发布

您现在位置:Python中文网/ 问答频道 /正文

__weakrefoffset__属性是什么?整数值表示什么?你知道吗

>>> int.__weakrefoffset__ 
0
>>> class A: 
...     pass 
... 
>>> A.__weakrefoffset__ 
24
>>> type.__weakrefoffset__ 
368
>>> class B: 
...     __slots__ = () 
...
>>> B.__weakrefoffset__
0

所有类型似乎都有这个属性。但是在docsPEP 205中都没有提到这一点。你知道吗


Tags: docs类型属性type整数passpepclass
2条回答

在CPython中,像float这样的简单类型的布局有三个字段:类型指针、引用计数和值(这里是double)。对于list,值是三个变量(指向单独分配的数组的指针、其容量和使用的大小)。这些类型不支持属性或弱引用以节省空间。你知道吗

如果一个Python类继承了其中的一个,那么它必须能够支持属性,而且没有固定的偏移量来放置__dict__指针(而不会因为将它放置在一个大的未使用偏移量而浪费内存)。所以字典存储在任何有空间的地方,它的偏移量(字节)是recorded in the type。对于大小可变的基类(如tuple,它直接包括它的所有指针),特别支持将__dict__指针存储在可变大小部分的末尾(例如type("",(tuple,),{}).__dictoffset__是-8)。你知道吗

弱引用的情况是exactly analogous,只是不支持可变大小类型的(子类)。0的__weakrefoffset__(这是C静态变量的默认值)表示不支持,因为对象的类型通常位于其布局的开头。你知道吗

PEP 205中引用:

Many built-in types will participate in the weak-reference management, and any extension type can elect to do so. The type structure will contain an additional field which provides an offset into the instance structure which contains a list of weak reference structures. If the value of the field is <= 0, the object does not participate. In this case, weakref.ref(), .setitem() and .setdefault(), and item assignment will raise TypeError. If the value of the field is > 0, a new weak reference can be generated and added to the list.

您可以在源代码here中看到它是如何工作的。你知道吗

查看另一个答案,了解它存在的原因。你知道吗

相关问题 更多 >