Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I am not sure of what the exact control flow inside the <code>ndarray</code>'s machinery is, but what's happening in your case is more or less clear:</p> <p>What <code>ndarray</code> is delegating to your object's <code>__rsub__</code> method is not the overall substraction operation, but the substraction of your object from each of the items in the array. And apparently when it has to delegate an operation to the object's methods, the return type is set to <code>object</code> regardless of what gets returned. You can check it with this slight modification of your code:</p> <pre><code>class test(object): def __sub__(self, other): return other def __rsub__(self, other): return other if other != 1 else 666 In [11]: t = test() In [12]: t - np.arange(4) Out[12]: array([0, 1, 2, 3]) In [13]: np.arange(4) - t Out[13]: array([0, 666, 2, 3], dtype=object) </code></pre> <p>I don't think there is an easy way of overriding this behaviour. You could try <a href="http://docs.scipy.org/doc/numpy/user/basics.subclassing.html#array-wrap-for-ufuncs" rel="nofollow">making <code>test</code> a subclass of <code>ndarray</code></a> with a high <code>__array_priority__</code> and abuse a little the <code>__array_wrap__</code> method:</p> <pre><code>class test(np.ndarray): __array_priority__ = 100 def __new__(cls): obj = np.int32([1]).view(cls) return obj def __array_wrap__(self, arr, context) : if context is not None : ufunc = context[0] args = context[1] if ufunc == np.subtract : if self is args[0] : return args[1] elif self is args[1] : return args[0] return arr </code></pre> <p>And now:</p> <pre><code>&gt;&gt;&gt; t = test() &gt;&gt;&gt; np.arange(4) - t array([0, 1, 2, 3]) &gt;&gt;&gt; t - np.arange(4) array([0, 1, 2, 3]) </code></pre> <p>But:</p> <pre><code>&gt;&gt;&gt; np.arange(4) + t test([1, 2, 3, 4]) &gt;&gt;&gt; t + np.arange(4) test([1, 2, 3, 4]) </code></pre> <p>It is a little bit wasteful, because we are doing the operation of adding the <code>1</code> inside <code>t</code> to every value in the array, and then silently discarding it, but I can't think of any way of overriding that.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload