为什么我必须显式继承插槽的对象才能像宣传的那样工作?

csv*_*van 3 python

我的一位同事最近向我展示了以下会议:

>>> class Foo:
...     __slots__ = ['x']
...     def __init__(self):
...             self.x = "x"
... 
>>> f = Foo()
>>> f.x
'x'
>>> f.y = 1
>>> class Bar(object):
...     __slots__ = ['x']
...     def __init__(self):
...             self.x = "x"
... 
>>> b = Bar()
>>> b.x
'x'
>>> b.y = 1
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AttributeError: 'Bar' object has no attribute 'y'
Run Code Online (Sandbox Code Playgroud)

根据Python文档,__slots__除非用户手动提供dict实例,否则定义应该使得不可能分配除插槽中指定的变量之外的任何其他变量:

文档没有提到明确需要从object类似的继承Bar.

为什么会这样?

Jam*_*sik 10

它确实说,只是不明确:

可以通过在新样式类定义中定义__slots__来覆盖默认值.

在Python 2中,当你继承时object,你正在创建一个新式的类.如果你不这样做,那就是一个旧式的课程.