Is it possible to numpy.vectorize an instance method?

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

    Simple solution without modifying the class

    You can use np.vectorize directly on the method on the instance:

    class Dummy(object):
    
        def __init__(self, val=1):
            self.val = val
    
        def f(self, x):
            if x == 0:
                return self.val
            else:
                return 2
    
    
    vec_f = np.vectorize(Dummy().f) 
    
    
    def test_3():
        assert list(vec_f([0, 1, 2])) == [1, 2, 2]
    
    test_3()
    

    You can also create a vectorized function vec_f in your __init__:

    Adding a vectorized version to the instance

    class Dummy(object):
    
        def __init__(self, val=1):
            self.val = val
            self.vec_f = np.vectorize(self.f) 
    
        def f(self, x):
            if x == 0:
                return self.val
            else:
                return 2
    
    
    def test_3():
        assert list(Dummy().vec_f([0, 1, 2])) == [1, 2, 2]
    

    or with a different naming scheme:

    class Dummy(object):
    
        def __init__(self, val=1):
            self.val = val
            self.f = np.vectorize(self.scalar_f) 
    
        def scalar_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]
    
    test_3()
    
        test_3()
    

提交回复
热议问题