1

Why does the Python interpreter allow me to change the __slots__ attribute for a class, but doesn't cause any change in the class's behavior?
Attempting to change an instance attribute causes: "AttribiuteError - attribute is read-only" - as I understand it.
But why does it allow me to change the class attribute, but it does not change the work of the class?
What exactly happened at this moment? my_object .__ class __.__ slots__ = ('c',)

>>> class MyClass:
...     __slots__ = ('a', 'b')
...
...     def __init__(self):
...             self.a = 1
...             self.b = 2
...
>>> my_object = MyClass()
>>> my_object.a
1
>>> my_object.b
2
>>> my_object.__slots__
('a', 'b')
>>> my_object.__class__.__slots__
('a', 'b')
>>> my_object.__slots__ = ('c',)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'MyClass' object attribute '__slots__' is read-only
>>> my_object.__class__.__slots__ = ('c',)
>>> my_new_object = MyClass()
>>> my_new_object.__slots__
('c',)
>>> my_new_object.__class__.__slots__
('c',)
>>> my_new_object.c
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'MyClass' object has no attribute 'c'
>>> my_new_object.a
1
>>> my_new_object.b
2
Marco
  • 81
  • 3
  • 7
  • 1
    Does this answer your question? [Dynamically change \_\_slots\_\_ in Python 3](https://stackoverflow.com/questions/27907373/dynamically-change-slots-in-python-3) – kaya3 Mar 08 '20 at 17:12
  • As an instance attribute - yes. And I understand that. But I still don't know why I can change __slots__ as the class attribute. And why didn't that give any effect. – Marco Mar 08 '20 at 17:23
  • 1
    Read [this answer](https://stackoverflow.com/a/27907928/12299000): *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. The fact that the original object that you set still remains as an attribute on the type is (perhaps) just a convenience for introspection.* – kaya3 Mar 08 '20 at 17:26

0 Answers0