There's some strange behavior with slots i currently do not understand. Using self.__slots__[0] = _value to set a value for the attribute define in the __slots__ list, the only way to read its value is by accessing the same element in the list self.__slots__[0].
If i were to attempt to access the value through a.slot_0, it results in an AttributeError. However setting the value through
self.slot_0 = _value
allows the value to be accessed by a.slot_0. What is the reasoning for this behavior?
It seems the list is being updated with the intended value for the string attribute, but even though the list attribute is overwritten e.g slot_0, the attribute remains on the instance's namespace shown by dir(a)
If this is intended behavior, to allow the __slots__ list to store the values for the initial attributes. While overwriting those attributes. Which method is preferable, mutating the list with values or initializing the attributes with values.
__slots__[o] = ... vs instance.Attribute = ...?
class Example3():
__slots__ = ["slot_0"]
def set_0(self, _value):
#self.slot_0 = _value
self.__slots__[0] = _value
def get_0(self):
return self.__slots__[0]
a = Example3()
b = Example3()
a.set_0("zero")
#print(a.get_0())
print(a.slot_0)
print(dir(a))
print(a.__slots__)
Traceback (most recent call last):
File "c:\Users\Dell\Desktop\PythonPlayground\slots.py", line 51, in <module>
print(a.slot_0)
AttributeError: 'Example3' object has no attribute 'slot_0'. Did you mean: 'set_0'?
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__',
'__ge__', '__getattribute__', '__gt__', '__hash__', '__init__',
'__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
'__slots__', '__str__', '__subclasshook__', 'get_0', 'set_0', 'slot_0']
['zero']