Array and __rmul__ operator in Python Numpy

前端 未结 3 926
太阳男子
太阳男子 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条回答
  •  Happy的楠姐
    2021-01-05 01:29

    I could not explain the underlying problem as precise as Bakuriu, but there might be another solution.

    You can force numpy to use your evaluation method by defining __array_priority__. As explained here in the numpy docs.

    In your case you had to change your class definition to:

    MAGIC_NUMBER = 15.0
    # for the necessary lowest values of MAGIC_NUMBER look into the numpy docs
    class foo(object):
        __array_priority__ = MAGIC_NUMBER
        aarg = 0
    
        def __init__(self):
            self.aarg = 1
    
    
        def __rmul__(self,A):
            print(A)
            return 0
    
        def __mul__(self,A):
            print(A)
            return 0
    

提交回复
热议问题