How to dynamically change __slots__ attribute?

后端 未结 4 883
梦毁少年i
梦毁少年i 2020-12-06 13:27

Suppose I have a class with __slots__

class A:
    __slots__ = [\'x\']

a = A()
a.x = 1   # works fine
a.y = 1   # AttributeError (as expected)
         


        
4条回答
  •  Happy的楠姐
    2020-12-06 14:08

    You cannot modify the __slots__ attribute after class creation. This is because it would leade to strange behaviour.

    Imagine the following.

    class A:
        __slots__ = ["x"]
    
    a = A()
    A.__slots__.append("y")
    a.y = None 
    

    What should happen in this scenario? No space was originally allocated for a second slot, but according to the slots attribute, a should be able have space for y.

    __slots__ is not about protecting what names can and cannot be accessed. Rather __slots__ is about reducing the memory footprint of an object. By attempting to modify __slots__ you would defeat the optimisations that __slots__ is meant to achieve.

    How __slots__ reduces memory footprint

    Normally, an object's attributes are stored in a dict, which requires a fair bit of memory itself. If you are creating millions of objects then the space required by these dicts becomes prohibitive. __slots__ informs the python machinery that makes the class object that there will only be so many attributes refered to by instances of this class and what the names of the attributes will be. Therefore, the class can make an optimisation by storing the attributes directly on the instance rather than in a dict. It places the memory for the (pointers to the) attributes directly on the object, rather than creating a new dict for the object.

提交回复
热议问题