How to get __radd__ to work with numpy arrays

Consider the following python code:

class MyClass:
   def __radd__(self, a):
      print "foo", a
      return a

p = MyClass()

To call radd, you can run the following:

>>> print "bar"+p
foo bar
bar

This is the expected behavior. __add__it starts up and fails, so it __radd__takes over and processes the situation. But with numpy arrays, it behaves a little differently:

>>> v = np.arange(2)
>>> print v+p
foo 0.
foo 1.
[0. 1.]

It seems that unlike the above example, v.__add__itterativly goes through the vcomponents and performs p.__radd__on them. In other words, he decided that the return type would be ndarray(until the code failed). I get that it is numpy that is trying to be smart, but somtimes I would like my class to handle aritmethics.

Is it possible to get standard behavior __radd__with numpy arrays?

+3
1

a+b, , : b.__radd__ , a.__add__ . , , , : b+a.

, , . numpy.ndarray __radd__, . , , .

+2

All Articles