
"To use __slots__, we need to define a __slots__ attribute on our class that points to a tuple of strings that represent valid attributes names for each instance of this class. Let's add __slots__ to our Point class: If we make a new instance of this Point class, we'll see that it has an x attribute (just as before): And we can change the value of this attribute (just as before):"
"But if we try to make a new attribute (an attribute that isn't x, y, or z), we'll get an AttributeError: We get an AttributeError because each instance of this class no longer has a __dict__ dictionary where it stores its attributes: Instead, __slots__ uses something kind of like a fixed-width list to store these attributes. So because we're using __slots__, we can't expand the number of attributes that are on each instance of this class."
"Normally, class instances store their attributes in a dictionary called __dict__. For our class, every instance has x, y, and z attributes: But we could add other attributes to any instance of this Point class: And another key-value pair will appear in our dictionary: This is how classes work by default. Unless you use __slots__."
Class instances store their attributes in a per-instance __dict__ by default, allowing arbitrary attributes to be added. Defining __slots__ as a tuple of attribute names restricts which attributes instances can have and removes the instance __dict__. Instances using __slots__ store attributes in a more compact, fixed-layout structure instead of a dictionary. Because the storage is more compact, memory usage is lower for many instances. Attribute access on __slots__ instances is typically slightly faster due to the simpler storage layout. The trade-off is that attributes cannot be dynamically added beyond the specified slots.
Read at Pythonmorsels
Unable to calculate read time
Collection
[
|
...
]