From the docs:
Many operations have an “in-place”
version. The following functions
provide a more primitive access to
in-place operators than the usual
syntax does; for example, the
statement x += y is equivalent to x =
operator.iadd(x, y). Another way to
put it is to say that z =
operator.iadd(x, y) is equivalent to
the compound statement z = x; z += y.
Questions:
-
Why isn’t
operator.iadd(x, y)equivalent toz = x; z += y? -
How does
operator.iadd(x, y)differ fromoperator.add(x, y)?
Related question, but I’m not interested in Python class methods; just regular operators on built-in Python types.
First, you need to understand the difference between
__add__and__iadd__.An object’s
__add__method is regular addition: it takes two parameters, returns their sum, and doesn’t modify either parameter.An object’s
__iadd__method also takes two parameters, but makes the change in-place, modifying the contents of the first parameter. Because this requires object mutation, immutable types (like the standard number types) shouldn’t have an__iadd__method.a + buses__add__.a += buses__iadd__if it exists; if it doesn’t, it emulates it via__add__, as intmp = a + b; a = tmp.operator.addandoperator.iadddiffer in the same way.To the other question:
operator.iadd(x, y)isn’t equivalent toz = x; z += y, because if no__iadd__exists__add__will be used instead. You need to assign the value to ensure that the result is stored in both cases:x = operator.iadd(x, y).You can see this yourself easily enough: