How to save memory by __slots__ in python

  • 2021-11-13 08:37:49
  • OfStack

Description

1. With _slots__ class attribute, instance attribute can be stored in meta zu, which greatly saves storage space.

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

If the instance supports weak references, you need to add __slots__ to __weakref.

Instances


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

Extension of knowledge points:

__slots__

If the __slots__ attribute is defined in a class, an instance of that class will not have the __dict__ attribute, and an instance without __dict__ cannot add an instance attribute. Simply put, the function of __slots__ is to prevent the class from assigning __dict__ attributes to an instance at instantiation time, limiting the attributes that the instance can add.

Action

Typically, instances use __dict__ to store their own properties, which allows instances to add or delete properties dynamically. However, there is no need to add variables dynamically for classes that already know what variables are available at compile time or that do not allow them to be added dynamically. What if you want to restrict instance attributes and don't want it to add attributes dynamically? For example, we only allow name and age attributes to be added to instances of A.

For this purpose, Python allows you to define a __slots__ variable when defining class to limit the attributes that can be added to an instance of the class.


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

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

The above is the python in __slots__ save memory specific method detailed content, more about python in __slots__ how to save memory information please pay attention to other related articles on this site!


Related articles: