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 :-)