Skip to content Skip to sidebar Skip to footer

Why Do Methods Of Classes That Inherit From Numpy Arrays Return Different Things?

Let's look at some very simple behaviour of numpy arrays: import numpy as np arr = np.array([1,2,3,4,5]) max_value = arr.max() # returns 5 Now I create a class which inherits from

Solution 1:

Following the numpy docs: array_wrap gets called at the end of numpy ufuncs and other numpy functions, to allow a subclass to set the type of the return value and update attributes and metadata.

class CustomArray(np.ndarray):
    def __new__(cls, a, dtype=None, order=None):
        obj = np.asarray(a, dtype, order).view(cls)
        return obj

    def __array_wrap__(self, out_arr, context=None):
        return np.ndarray.__array_wrap__(self, out_arr, context)

c = CustomArray([1,2,3,4])
c.max() # returns 4

Post a Comment for "Why Do Methods Of Classes That Inherit From Numpy Arrays Return Different Things?"