Array and __rmul__ operator in Python Numpy

前端 未结 3 949
太阳男子
太阳男子 2021-01-05 01:10

In a project, I created a class, and I needed an operation between this new class and a real matrix, so I overloaded the __rmul__ function like this

<         


        
3条回答
  •  情书的邮戳
    2021-01-05 01:24

    You can define __numpy_ufunc__ function in your class. It works even without subclassing the np.ndarray. You can find the documentation here.

    Here is an example based on your case:

    class foo(object):
    
        aarg = 0
    
        def __init__(self):
            self.aarg = 1
    
        def __numpy_ufunc__(self, *args):
            pass
    
        def __rmul__(self,A):
            print(A)
            return 0
    
        def __mul__(self,A):
            print(A)
            return 0
    

    And if we try it,

    A = [[i*j for i in np.arange(2)  ] for j in np.arange(3)]
    A = np.array(A)
    R = foo()
    C =  A * R
    

    Output:

    [[0 0]
     [0 1]
     [0 2]]
    

    It works!

提交回复
热议问题