为什么Python中的对象不能添加属性?
(用Python shell编写)
>>> o = object()
>>> o.test = 1
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
o.test = 1
AttributeError: 'object' object has no attribute 'test'
>>> class test1:
pass
>>> t = test1()
>>> t.test
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
t.test
AttributeError: test1 instance has no attribute 'test'
>>> t.test = 1
>>> t.test
1
>>> class test2(object):
pass
>>> t = test2()
>>> t.test = 1
>>> t.test
1
>>>
为什么对象不允许你向它添加属性?
(Written in Python shell)
>>> o = object()
>>> o.test = 1
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
o.test = 1
AttributeError: 'object' object has no attribute 'test'
>>> class test1:
pass
>>> t = test1()
>>> t.test
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
t.test
AttributeError: test1 instance has no attribute 'test'
>>> t.test = 1
>>> t.test
1
>>> class test2(object):
pass
>>> t = test2()
>>> t.test = 1
>>> t.test
1
>>>
Why doesn't object allow you to add attributes to it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请注意,
object
实例没有__dict__
属性:在派生类中说明此行为的示例:
引用
槽
:编辑:为了从评论中回答 ThomasH,OP 的测试类是一个“旧式”类。 尝试一下:
您会注意到有一个 __dict__ 实例。 对象类可能没有定义
__slots__
,但结果是相同的:缺少__dict__
,这就是阻止属性动态分配的原因。 我重新组织了我的答案以使这一点更清楚(将第二段移至顶部)。Notice that an
object
instance has no__dict__
attribute:An example to illustrate this behavior in a derived class:
Quoting from the docs on
slots
:EDIT: To answer ThomasH from the comments, OP's test class is an "old-style" class. Try:
and you'll notice there is a
__dict__
instance. The object class may not have a__slots__
defined, but the result is the same: lack of a__dict__
, which is what prevents dynamic assignment of an attribute. I've reorganized my answer to make this clearer (move the second paragraph to the top).好问题,我的猜测是,这与
object
是内置/扩展类型这一事实有关。IIRC,这与 __dict__ 属性的存在有关,或者更正确地说,当对象没有 __dict__< 时,
setattr()
会爆炸。 /代码> 属性。Good question, my guess is that it has to do with the fact that
object
is a built-in/extension type.IIRC, this has to do with the presence of a
__dict__
attribute or, more correctly,setattr()
blowing up when the object doesn't have a__dict__
attribute.