2 ms·
by far most python objects use the __dict__ mechanism, not just dicts. For example: >>> class MyFoo: ... pass ... >>> foo=MyFoo() >>> f
by Doxin 6y ago
by far most python objects use the __dict__ mechanism, not just dicts. For example:
>>> class MyFoo:
... pass
...
>>> foo=MyFoo()
>>> foo.bar='baz'
>>> foo.__dict__
{'bar': 'baz'}
>>> foo.__dict__['bar']=42
>>> foo.bar
42
__slots__ is an alternative in case your object has a fixed number of member variables. It's mostly a memory optimization:
>>> class MyFoo:
... __slots__=['bar']
...
>>> f=MyFoo()
>>> f.bar='baz'
>>> f.__dict__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'MyFoo' object has no attribute '__dict__'
Some types of objects have neither, these tend to be builtins or objects implemented using the C API:
>>> foo = int()
>>> foo.__dict__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute '__dict__'
>>> foo.__slots__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute '__slots__'
- vlovich123 6y agoThanks for the clarification. I always wished Python would make it easier somehow to auto-detect the slots from the constructor. I don’t think it’s just a memory optimization though since they mention access of when slots is defined things are faster and benefit more from this optimization.