safetyduck
safetyduck

Reputation: 6874

numpy python class calling wrong __setitem__

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.

Upvotes: 2

Views: 396

Answers (1)

unutbu
unutbu

Reputation: 880547

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.

import numpy as np

class AutoArray2(np.ndarray):
    def __new__(cls, input_array):
        # Input array is an already formed ndarray instance
        # We first cast to be our class type
        obj = np.asarray(input_array).view(cls)
        return obj
    def __array_finalize__(self, obj):
        if obj is None: return
    def __setitem__(self, coords, value):
        print("HERE")

a = np.array([[1,2],[2,3]])
b = AutoArray2(a)
b[0,0] = 1

yields

HERE

The key ingredient is the call to view(cls). Without it, you are returning a plain ndarray, not an AutoArray2 instance.

Also, a[0,0] = 1 is using a -- the plain ndarray. To use b's __setitem__ you need b[0,0] = 1.

Upvotes: 3

Related Questions