In Python, I can add an attribute to a class Cthat I previously defined. However, I cannot add the attribute to list- the error message that appears explains that this is because it listis a built-in type:
>>> 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'
Similarly, you can add an attribute to an instance C, but not to an instance list. In this case, however, the error message is much more vague:
>>> 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'
Why can't I add members to instances list? Is this again because it listis an inline type?
In general, what objects in Python can have attributes added dynamically?
source
share