在Python中,我可以向之前定义的类
同样地,可以向
为什么我不能向
更一般地说,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中哪些对象可以动态添加属性?