2

默认情况下,插槽是可写的:

>>> class A: __slots__ = ('x',)
... 
>>> list(vars(A))
['__module__', '__slots__', 'x', '__doc__']
>>> vars(A)['x']
<member 'x' of 'A' objects>
>>> a = A()
>>> a.x = 'foo'
>>> del a.x

如何创建只读插槽,如插槽'__thisclass__'、、'__self__''__self_class__'super

>>> list(vars(super))
['__repr__', '__getattribute__', '__get__', '__init__', '__new__',
 '__thisclass__', '__self__', '__self_class__', '__doc__']
>>> vars(super)['__thisclass__']
<member '__thisclass__' of 'super' objects>
>>> s = super(int, 123)
>>> s.__thisclass__ = float
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: readonly attribute
>>> del s.__thisclass__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: readonly attribute
4

1 回答 1

6

您不能,Python 代码中没有选项可以创建只读描述符,例如用于 的描述符等__thisclass__

PyMemberDef在 C API 中,所有插槽都使用相同的描述符对象类型,对于设置flagsREADONLY.

例如,super您识别的描述符在super_members数组中定义:

static PyMemberDef super_members[] = {
    {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
     "the class invoking super()"},
    {"__self__",  T_OBJECT, offsetof(superobject, obj), READONLY,
     "the instance invoking super(); may be None"},
    {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
     "the type of the instance invoking super(); may be None"},
    {0}
};

正在处理时__slots__,没有可以设置此标志的路径;中的代码type.__new__只设置了前三个值,分别nametypeoffset

    mp = PyHeapType_GET_MEMBERS(et);
    slotoffset = base->tp_basicsize;
    if (et->ht_slots != NULL) {
        for (i = 0; i < nslots; i++, mp++) {
            mp->name = PyUnicode_AsUTF8(
                PyTuple_GET_ITEM(et->ht_slots, i));
            if (mp->name == NULL)
                goto error;
            mp->type = T_OBJECT_EX;
            mp->offset = slotoffset;


            /* __dict__ and __weakref__ are already filtered out */
            assert(strcmp(mp->name, "__dict__") != 0);
            assert(strcmp(mp->name, "__weakref__") != 0);


            slotoffset += sizeof(PyObject *);
        }
    }

以供参考:

  • PyHeapType_GET_MEMBERS访问PyMemberDef正在创建的新类型对象的数组。它已经分配了正确数量的插槽。
  • et->ht_slots是插槽名称的元组。
  • slotoffset是实例对象内存区域的相对偏移量,用于存储插槽内容。
  • 该字段的T_OBJECT_EXtype意味着该插槽存储指向 Python 对象的指针,如果指针设置为NULLan,AttributeError则在您尝试获取该值时引发。

请注意,如果可以将这些插槽设置只读,您还需要一种机制来在创建新实例之前提供它们的值!毕竟,如果阻止所有 Python 代码在实例上设置只读属性,那么您的 Python 类将如何设置初始值?

于 2021-04-09T18:38:58.847 回答