I have the following code:
class VectorN(object):
def __init__(self, param):
if isinstance(param, int):
self.dim = param
self.data = [0.0] * param
elif isinstance(param, tuple):
self.dim = 3
self.data = param
#else:
#raise TypeError("You must pass an int or sequence!")
def __str__(self):
return "<Vector" + str(self.dim) + ": " + str(self.data) + ">"
def __len__(self):
return len(self.data)
def __setitem__(self, key, item):
self.data[key] = item
Now when i try to call the __setitem__ method using the following code,
w = VectorN((1.2, "3", 5))
w.setitem(0, 9.9)
print(z)
print(w)
print(z[0])
print(len(v))
it gives me:
AttributeError: ‘VectorN’ object has no attribute ‘setitem’
That’s because
__setitem__is a magic method. It’s a special function that allows you to create container objects.Because it’s a magic method, you need not call it directly by its name- rather, built-in aspects of the Python language control its behavior. Note that it’s still just a normal method; you could call it by name, but then the syntax would be
w.__setitem__(0, 9.9).By defining
__setitem__you can instead set a value like so:w[0] = 9.9.__setitem__, from A Guide to Python’s Magic Methods: