Is it possible to numpy.vectorize an instance method?

前端 未结 5 470
我在风中等你
我在风中等你 2021-01-17 08:51

I\'ve found that the numpy.vectorize allows one to convert \'ordinary\' functions which expect a single number as input to a function which can also convert a list of inputs

5条回答
  •  走了就别回头了
    2021-01-17 09:28

    If you want to use vectorized implementation of your method you can use excluded parameter like following:

    class MyClass:
        def __init__(self, data):
            self.data = data
            self.my_vectorized_func = np.vectorize(self.my_func, excluded='self')
    
        def my_func(self, x):
            return pow(x, self.data)
    

    With this, you can use your method like the non-vectorized one:

     In[1]: myclass = MyClass(3) # '3' will be the power factor of our function
     In[2]: myclass.my_vectorized_func([1, 2, 3, 4, 5])
    Out[3]: array([  1,   8,  27,  64, 125])
    

提交回复
热议问题