
"Let's talk about how to optimize the memory usage and the attribute lookup time of our Python classes. How are class attributes stored by default? Here we have a class called Point in a points.py file: And here's an instance of this Point class: Normally, classes store their attributes in a dictionary called __dict__. We have a class here where every instance has x, y, and z attributes."
"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 our class. Let's add __slots__ to our Point class: This instance of our Point class has an x attribute (just as before): 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:"
Classes store instance attributes in a per-instance dictionary named __dict__, allowing arbitrary attributes to be added and producing new key-value pairs. Defining __slots__ as a tuple of valid attribute names replaces per-instance __dict__ storage with fixed-slot storage for those attribute names. Instances of classes with __slots__ allow only the declared attributes and raise AttributeError on attempts to assign undeclared ones. __slots__ prevents dynamic attribute expansion and uses a compact, fixed layout similar to a list of slots. __slots__ is typically used to save memory and can improve attribute lookup time.
Read at Pythonmorsels
Unable to calculate read time
Collection
[
|
...
]