Skip to content Skip to sidebar Skip to footer

Numpy Inheritance; Add A Method To Numpy Array

Let's say we have a 2D array, image, eg. 20x20. I would like add a method, called 'imshow' to this object such that whenever I do image.imshow(**kwargs)), the method imshow will ma

Solution 1:

Just found the answer (thanks to How can a class that inherits from a NumPy array change its own values?)!

class array(np.ndarray):

    def __new__(cls, a):
        obj = np.asarray(a).view(cls)
        return obj

    def imshow(self, **kwargs):
        plt.figure()
        plt.imshow(self, **kwargs)
        plt.show()

Post a Comment for "Numpy Inheritance; Add A Method To Numpy Array"