请注意,object
实例没有__dict__
属性:
>>> dir(object())
['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__']
一个在派生类中说明此行为的示例:
>>> class Foo(object):
... __slots__ = {}
...
>>> f = Foo()
>>> f.bar = 42
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'bar'
引用以下文档slots
:
[…]__slots__
声明采用一系列实例变量,并在每个实例中仅保留足够的空间来为每个变量保存一个值。因为__dict__
未为每个实例创建空间,所以节省了空间。
编辑:要从评论中回答ThomasH,OP的测试类是“旧式”类。尝试:
>>> class test: pass
...
>>> getattr(test(), '__dict__')
{}
>>> getattr(object(), '__dict__')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute '__dict__'
您会注意到有一个__dict__
实例。对象类可能没有__slots__
定义,但是结果是相同的:缺少__dict__
,这是阻止属性动态分配的原因。我重新整理了答案,以使这一点更清楚(将第二段移到顶部)。