I assumed that square bracket assignment is a syntactic sugar for __setitem__
magic-method. But as you can see from the result of this snippet it is not.
class A(object):
def __init__(self):
self.value = None
def __setitem__(self, key, value):
self.value = value
class B(object):
def __init__(self):
self.a = A()
def __getattr__(self, name):
attribute = getattr(self.a, name)
setattr(self, name, attribute)
return getattr(self, name)
if __name__ == '__main__':
b = B()
b.__setitem__((1, 2), 4)
b[1, 2] = 4
TypeError: 'B' object does not support item assignment
Could someone explain why square bracket assignment is not the same as __setitem__
method calling?