问题
I have a custom class which defines custom, commutative, behaviour for the binary +
operator:
class foo(object):
def __add__(self, other):
...
__radd__ = __add__
It is designed to deal with scalars and with numpy
arrays in its own way---a way that is intentionally different from the way numpy
adds arrays.
If I start with the following:
f = foo()
a = numpy.array([1, 2, 3])
c = 4
then all is well if I do f + a
, f + c
or c + f
, in the sense that I get the custom behaviour I want in all cases. However a + f
gets me a different result (and in some situations an exception) because the numpy
array method a.__add__
takes over. I understand that __radd__
is "only called if the left operand does not support the corresponding operation" per the Python docs. I also read somewhere that this is overridden if a.__add__
returns NotImplemented
.
So is there any way of telling numpy
"hey, I got this, you should return NotImplemented
when asked to add a foo
"? In Matlab this would be accomplished by superiorto
. Is there any equivalent in numpy
? (NB: I don't want to have to subclass numpy.ndarray
---I want to be able to deal with numpy
arrays as they come.)
[In an ideal world I would like to be able to cope with native Python objects in the same way, such that [1,2,3] + foo()
gave the same result as foo() + [1,2,3]
---but I'm guessing it's got to be impossible to disable list.__add__
selectively based on the class of the right operand. Right?]
来源:https://stackoverflow.com/questions/47600049/how-if-at-all-can-binary-operator-methods-of-numpy-arrays-be-overridden-by-the