2


I have a question concerning overriding operands. I just tried to override the __add__(self, other) operator in a custom class, such that on of its elements (a numpy array) can be added to another numpy array. To make both directions of summing possible I both declared the __add__as well as the __radd__ operator. A small example:

import numpy as np

class MyClass():
    def __init__(self, x):
        self.x = x
        self._mat = self._calc_mat()


    def _calc_mat(self):
        return np.eye(2)*self.x

    def __add__(self, other):
        return self._mat + other

    def __radd__(self, other):
        return self._mat + other


def some_function(x):
    return x + np.ones(4).reshape((2,2))

def some_other_function(x):
    return np.ones(4).reshape((2,2)) + x


inst = MyClass(3)

some_function(x=inst)
some_other_function(x=inst)

Strangely, I get two different outputs. The first ouput, from some_function is just like expected:

Out[1]
array([[ 4.,  1.],
       [ 1.,  4.]])

The second output gives me something odd:

Out[2]:    
array([[array([[ 4.,  1.],
       [ 1.,  4.]]),
        array([[ 4.,  1.],
       [ 1.,  4.]])],
       [array([[ 4.,  1.],
       [ 1.,  4.]]),
        array([[ 4.,  1.],
       [ 1.,  4.]])]], dtype=object)

Does somebody have an idea why is that?
Thanks, Markus :-)

1 Answer 1

2

the issue is that numpy array is also implementing an __add__ method, and it is called before your __radd__

you can see this answer for a solution: https://stackoverflow.com/a/22633052/7033869

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.