SoFunction
Updated on 2024-11-15

Specific ways to save memory with __slots__ in python

clarification

1. Using the _slots__ class attribute, you can store instance attributes in metazu, which greatly saves storage space.

2. All attributes must be defined as __slots__ tuples, and subclasses must also define __slots__.

Instances that support weak references need to add __slots__ to __weakref.

an actual example

class Vector2d:
    __slots__ = ('__x', '__y')
 
    typecode = 'd'

Knowledge Point Expansion:

__slots__

If the __slots__ attribute is defined in a class, instances of that class will not have the __dict__ attribute, and instances without __dict__ will not be able to add instance attributes. In short, what __slots__ does is prevent the class from assigning the __dict__ attribute to the instance at instantiation time, limiting the attributes that can be added to that instance.

corresponds English -ity, -ism, -ization

Typically instances use __dict__ to store their attributes, which allows instances to dynamically add or remove attributes. However, for classes that already know what variables are available at compile time or classes that don't allow variables to be added dynamically, they don't need to add variables dynamically. What if you want to restrict instance attributes and don't want it to add attributes dynamically? For example, let's say we only allow the name and age attributes to be added to instances of A.

To accomplish the above, Python allows a __slots__ variable to be defined when defining a class to limit the attributes that can be added to instances of that class.

class A(object):
  __slots__ = ('age','name')
a = A()
 = 'xiaoming'
 = 10
 = 123456 #error  AttributeError: 'A' object has no attribute 'id'

Since id is not in __slots__, instances cannot add an id attribute. Any attempt to add an attribute to the instance whose name is not in __slots__ will trigger an AttributeError exception.

The above is the details of __slots__ in python to save memory, more information about __slots__ in python how to save memory please pay attention to my other related articles!