What objects in Python can have added attributes dynamically?

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?

+4
source share
2 answers

__dict__. __dict__ - , . :

  • __dict__.
  • __dict__ .

, . :

  • , . int, str, list, bytes,... , ( )
  • , numpy stuff.
  • Python, __slots__. - __dict__ . , ( ).

, ? , . __dict__:

>>> class Example:
        pass
>>> class SlotsExample:
        __slots__ = ['x']

>>> hasattr(Example(), '__dict__')
True
>>> hasattr(SlotsExample(), '__dict__')
False
>>> hasattr(list, '__dict__')
True
>>> hasattr([], '__dict__')
False

__dict__ :

>>> isinstance(Example().__dict__, dict)
True
>>> isinstance(list.__dict__, dict)
False
+1

, __setattr__.

Python __getattr__ __setattr__. , . ( .)

/ (HEAPTYPE CPython) - , , , , . ( Python.)

0

Source: https://habr.com/ru/post/1686781/


All Articles