添加属性Python对象 [英] Adding attributes to python objects
问题描述
这是窃听我一会儿的事。为什么我不能做的:
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?
推荐答案
您可以添加属性有任何对象的 __ __字典
。
You can add attributes to any object that has a __dict__
.
-
X =对象()
没有它,例如。 - 字符串等简单的内置对象也没有了。
- 使用类
__ __插槽
也没有了。 - 与
类
定义的类有它,除非previous声明适用。
x = object()
doesn't have it, for example.- Strings and other simple builtin objects also don't have it.
- Classes using
__slots__
also do not have it. - Classes defined with
class
have it unless the previous statement applies.
如果一个对象是使用 __插槽__
/不具有 __字典__
,它通常是为了节省空间。例如,在 STR
这将是矫枉过正有字典 - 想象膨胀量在很短的字符串
If an object is using __slots__
/ doesn't have a __dict__
, it's usually to save space. For example, in a str
it would be overkill to have a dict - imagine the amount of bloat for a very short string.
如果你想测试一个给定的对象有一个 __字典__
,您可以用 hasattr(OBJ,'__dict __')
。
If you want to test if a given object has a __dict__
, you can use hasattr(obj, '__dict__')
.
<一个href=\"http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#the-dynamic-dict\">This也可能是有趣的阅读:
This might also be interesting to read:
一些对象,如内建类型及其实例(列表,元组等)不具有 __ __字典
。因此用户定义的属性不能对它们进行设置。
Some objects, such as built-in types and their instances (lists, tuples, etc.) do not have a
__dict__
. Consequently user-defined attributes cannot be set on them.
有关Python的包括数据模型的另一个有趣的文章 __字典__
, __插槽__
等是的这个从Python参考
Another interesting article about Python's data model including __dict__
, __slots__
, etc. is this from the python reference.
这篇关于添加属性Python对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!