How do you add a method to a subclass of ndarray with __array_finalize__?

Viewed 44

I am looking at this example of subclassing numpy's ndarray class.

import numpy as np

class RealisticInfoArray(np.ndarray):

    def __new__(cls, input_array, info=None):
        # Input array is an already formed ndarray instance
        # We first cast to be our class type
        obj = np.asarray(input_array).view(cls)
        # add the new attribute to the created instance
        obj.info = info
        # Finally, we must return the newly created object:
        return obj

    def __array_finalize__(self, obj):
        # see InfoArray.__array_finalize__ for comments
        if obj is None: return
        self.info = getattr(obj, 'info', None)

How do I add a method to this subclass that can work on input_array, in a simple case: determine the maximum value in input_array (Let's ignore the fact that ndarray already possesses such a method). I have seen this answer. However, from my understanding, that only works for explicit constructor calls and misses the cases "view casting" and "new from template". A very naive attempt would be adding

    def SetMax(self):
        self.maximum = np.nanmax(self)

I think that this does not work since self is the pointer to the RealisticInfoArray instance and not the ndarray that is behind it. Iteration does not work either. However, changing one of the elements is possible.

    def ChangeValue(self):
        self[1]=0

I have thought about writing a static method

    @staticmethod
    def SetMax(a)
        return np.nanmax(a)

but I have no idea whether to call it in __new__, __array_finalize__ or both in order to set self.maximum. I think in __array_finalize__ would be enough but which argument do I provide? Both self and obj are pointers...

0 Answers
Related