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