向 python 对象添加属性
这是一件困扰我一段时间的事情。为什么我不能做:
>>> a = ""
>>> a.foo = 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'foo'
...而我可以做以下事情?
>>> class Bar():
... pass
...
>>> a = Bar()
>>> a.foo = 10 #ok!
这里有什么规则?您能给我一些描述吗?
It's a thing that bugged me for a while. Why can't I do:
>>> a = ""
>>> a.foo = 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'foo'
...while I can do the following?
>>> class Bar():
... pass
...
>>> a = Bar()
>>> a.foo = 10 #ok!
What's the rule here? Could you please point me to some description?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以向任何具有 __dict__ 的对象添加属性。
x = object()
就没有它。class
定义的类都具有它。如果一个对象使用 __slots__ / 没有 __dict__ ,通常是为了节省空间。例如,在
str
中,拥有一个字典就太过分了——想象一下非常短的字符串的膨胀量。如果要测试给定对象是否具有
__dict__
,可以使用hasattr(obj, '__dict__')
。这读起来可能也很有趣:
另一篇关于Python数据模型(包括
__dict__
、__slots__
等)的有趣文章是this 来自 python 参考。You can add attributes to any object that has a
__dict__
.x = object()
doesn't have it, for example.__slots__
also do not have it.class
have it unless the previous statement applies.If an object is using
__slots__
/ doesn't have a__dict__
, it's usually to save space. For example, in astr
it would be overkill to have a dict - imagine the amount of bloat for a very short string.If you want to test if a given object has a
__dict__
, you can usehasattr(obj, '__dict__')
.This might also be interesting to read:
Another interesting article about Python's data model including
__dict__
,__slots__
, etc. is this from the python reference.