Numpy Inheritance; add a method to Numpy Array

两盒软妹~` 提交于 2021-01-29 06:04:06

问题


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 make a call of Matplotlib.pyplot.imshow

What is the best way to do this? I was thinking of writing a class with an inheritance from numpy.ndarray, and adding a method 'imshow'.


回答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()


来源:https://stackoverflow.com/questions/61765603/numpy-inheritance-add-a-method-to-numpy-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!