Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>For the <code>+</code> operator, Python defines three "special" methods that an object may implement:</p> <ul> <li><code>__add__</code>: adds two items (<code>+</code> operator). When you do <code>a + b</code>, the <code>__add__</code> method of <code>a</code> is called with <code>b</code> as an argument.</li> <li><code>__radd__</code>: reflected add; for <code>a + b</code>, the <code>__radd__</code> method of <code>b</code> is called with <code>a</code> as an instance. This is only used when <code>a</code> doesn't know how to do the add and the two objects are different types.</li> <li><code>__iadd__</code>: in-place add; used for <code>a += b</code> where the result is assigned back to the left variable. This is provided separately because it might be possible to implement it in a more efficient way. For example, if <code>a</code> is a list, then <code>a += b</code> is the same as <code>a.extend(b)</code>. However, in the case of <code>c = a + b</code> you have to make a copy of <code>a</code> before you extend it since <code>a</code> is not to be modified in this case. Note that if you don't implement <code>__iadd__</code> then Python will just call <code>__add__</code> instead.</li> </ul> <p>So since these different operations are implemented with separate methods, it is possible (but generally bad practice) to implement them so they do totally different things, or perhaps in this case, only <em>slightly</em> different things.</p> <p>Others have deduced that you're using NumPy and explained its behavior. However, you asked about the underlying implementation. Hopefully you now see <em>why</em> it is sometimes the case that <code>a += b</code> is not the same as <code>a = a + b</code>. By the way, a similar trio of methods may also be implemented for other operations. See <a href="http://docs.python.org/reference/datamodel.html#object.__iadd__">this page</a> for a list of all the supported in-place methods.</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