Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h2>Emulating numeric types in Python (<a href="http://docs.python.org/2/reference/datamodel.html#emulating-numeric-types" rel="nofollow">docs</a>)</h2> <p>When the expression <code>a + b</code> is evaluated, first <code>a</code> is checked an <code>__add__</code> implementation; if it has one, <code>a.__add__(b)</code> is executed. If it doesn't, or running <code>a.__add__(b)</code> returns the special value <code>NotImplemented</code>, then <code>b</code> is checked for an <code>__radd__</code> implementation; if it doesn't have one or it returns <code>NotImplemented</code>, you can't add them.</p> <h2>What's going on in your code</h2> <p>A reminder of our objects:</p> <pre><code>&gt;&gt;&gt; a = adder(adder2(10)) &gt;&gt;&gt; a.value adder2 &gt;&gt;&gt; a.value.value 10 &gt;&gt;&gt; b = adder(adder2(12)) &gt;&gt;&gt; b.value adder2 b.value.value 12 </code></pre> <p><code>print a + b</code> could be described as:</p> <pre><code>a.__add__(b) which adder.__add__ implements as a.value.__add__(b) which adder2.__add__ implements as a.value.value + b so first we try a.value.value.__add__(b) but int.__add__ fails (returns NotImplemented) so we try b.__radd__(a.value.value) which adder.__radd__ implemented as b.value.__radd__(a.value.value) which adder2.__radd__ implements as a.value.value + b.value.value which int.__add__ implements as addition </code></pre> <h2>What to do about it</h2> <p>I think you're trying to create a type which can be added to numbers, or other objects of its type. If so, you want</p> <pre><code>class Adder(object): def __init__(self, value): self.value def __add__(self, other): return self.value + other def __radd__(self, other): return self.value + other </code></pre> <p>which is equivalent to the version without <code>+</code>:</p> <pre><code>class Adder(object): def __init__(self, value): self.value def __add__(self, other): r = self.value.__add__(other) if r is NotImplemented: r = other.__radd__(self.value) # so if other is a adder, use its __radd__ return r # since our value's __add__ will return __radd__ = __add__ </code></pre>
 

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