From https://stackoverflow.com/a/1529099/156458
To support arbitrary attribute assignment, an object needs a
__dict__: a dict associated with the object, where arbitrary attributes can be stored. Otherwise, there's nowhere to put new attributes.An instance of
objectdoes not carry around a__dict__-- if it did, before the horrible circular dependence problem (since__dict__, like most everything else, inherits fromobject;-), this would saddle every object in Python with a dict, which would mean an overhead of many bytes per object that currently doesn't have or need a dict (essentially, all objects that don't have arbitrarily assignable attributes don't have or need a dict).
...
When the class has the
__slots__special attribute (a sequence of strings), then theclassstatement (more precisely, the default metaclass,type) does not equip every instance of that class with a__dict__(and therefore the ability to have arbitrary attributes), just a finite, rigid set of "slots" (basically places which can each hold one reference to some object) with the given names.
If an object doesn't have __dict__, must its class have a __slots__ attribute?
For example, an instance of object doesn't have a __dict__:
>>> object().__dict__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute '__dict__'
but it doesn't have __slots__ either:
>>> object.__slots__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'object' has no attribute '__slots__'
Do object instances have any attributes at all?
How many possibilities are there:
- an object has
__dict__, and its class has__dict__but no__slots__ - an object doesn't have
__dict__, and its class has__slots__ - an object doesn't have
__dict__, and its class doesn't have__slots__?
Is it possible to tell if an object has __dict__ from its class?
if its class has
__slots__, then it doesn't have__dict__, correct?if its class doesn't have
__slots__, how can I tell if it has__dict__or not?