Is it possible to numpy.vectorize an instance method?

前端 未结 5 512
我在风中等你
我在风中等你 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:29

    Remembering a technique I saw in the memoized decorator, I managed to get the decorator to also work for instance methods by subclassing numpy.vectorize as follows:

    import numpy as np
    import functools
    
    
    class vectorize(np.vectorize):
        def __get__(self, obj, objtype):
            return functools.partial(self.__call__, obj)
    

    Now if I decorate the Dummy class' f method with vectorize instead of np.vectorize, the test passes:

    class Dummy(object):
        def __init__(self, val=1):
            self.val = val
    
        @vectorize
        def f(self, x):
            if x == 0:
                return self.val
            else:
                return 2
    
    
    def test_3():
        assert list(Dummy().f([0, 1, 2])) == [1, 2, 2]
    
    if __name__ == "__main__":
        pytest.main([__file__])
    

    with output

    test_numpy_vectorize.py .
    
    =========================== 1 passed in 0.01 seconds ===========================
    [Finished in 0.7s]
    

提交回复
热议问题