【发布时间】:2017-10-03 01:16:14
【问题描述】:
在 Python 中,我可以将属性添加到我之前定义的类 C。但是,我无法向 list 添加属性 - 生成的错误消息说明这是因为 list 是内置类型:
>>> class C: pass
...
>>> C.foo = 1
>>> C.foo
1
>>> list.foo = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'list'
同样,可以将属性添加到C 的实例,但不能添加到list 的实例。然而,在这种情况下,错误信息更加模糊:
>>> o = C()
>>> o.bar = 2
>>> o.bar
2
>>> o = []
>>> o.bar = 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'bar'
为什么我不能向list 的实例添加成员?还是因为list 是内置类型吗?
更一般地说,Python 中的哪些对象可以动态添加属性?
【问题讨论】:
-
我猜任何不是内置类型的东西
-
一般不是内置类型。唯一令人惊讶的是,您可以为普通函数添加属性。 Google for PEP 232。
标签: python oop object dynamic attributes