I have the following class:
class autoArray2(numpy.ndarray):
def __new__(self, *args, **kwargs):
obj = numpy.array(*args, **kwargs)
return(obj)
def __setitem__(self, coords, value):
print("HERE")
However it seems the array.__setitem__ is being called instead of the one I’ve specified.
a = numpy.array([[1,2],[2,3]])
b = autoArray2(a)
a[0,0] = 1
“HERE” is not printed.
Subclassing a numpy array is a little bit tricky.
Stefan van der Walt’s slides and the numpy docs
are good places to begin if you want to subclass.
yields
The key ingredient is the call to
view(cls). Without it, you are returning a plainndarray, not an AutoArray2 instance.Also,
a[0,0] = 1is usinga— the plainndarray. To useb‘s__setitem__you needb[0,0] = 1.