How to dynamically change __slots__ attribute?

后端 未结 4 880
梦毁少年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条回答
  •  萌比男神i
    2020-12-06 13:56

    It appears to me a type turns __slots__ into a tuple as one of it's first orders of action. It then stores the tuple on the extended type object. Since beneath it all, the python is looking at a tuple, there is no way to mutate it. Indeed, I'm not even sure you can access it unless you pass a tuple in to the instance in the first place.

    The fact that the original object that you set still remains as an attribute on the type is (perhaps) just a convenience for introspection.

    You can't modify __slots__ and expect to have that show up somewhere (and really -- from a readability perspective, You probably don't really want to do that anyway, right?)...

    Of course, you can always subclass to extend the slots:

    >>> class C(A):
    ...   __slots__ = ['z']
    ... 
    >>> c = C()
    >>> c.x = 1
    >>> c.z = 1
    

提交回复
热议问题