考虑一个简单的类:
class A:
__slots__ = ('a',)
a 是什么?这是一个描述符:
>>> type(A.a)
<class 'member_descriptor'>
__slots__ 值中的每个字符串都用于创建具有 member_descriptor 值的该名称的类属性。
这意味着您可以(尝试)通过A.a.__get__访问它
>>> a = A()
>>> a.a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: a
用A.a.__set__分配给它
>>> a.a = 7
并尝试再次访问它:)
>>> a.a
7
你不能做的是尝试分配给实例上的任何其他属性:
>>> A.b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'A' has no attribute 'b'
>>> a.b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'b'
>>> a.b = 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'b'
__slots__ 的存在不仅创建了请求的类属性,而且防止在实例上创建任何其他属性。