Augmented Assignment

Augmented assignment refers to the use of operators, which imply both an arithmetic operation as well as an assignment. You will recognize the following symbols if you are a C, C++, or Java programmer:

+=        -=         *=        /=         %=        **=
<<=       >>=           &=        ^=         |=

For example, the shorter

A += B

can now be used instead of

A = A + B

Other than the obvious syntactical change, the most significant difference is that the first object (A in our example) is examined only once. Mutable objects will be modified in place, whereas immutable objects will have the same effect as “A = A + B” (with a new object allocated) except that A is only evaluated once, as we have mentioned before.

>>> m = 12
>>> m %= 7
>>> m
5
>>> m **= 2
>>> m
25
>>> aList = [123, 'xyz']
>>> aList += [45.6e7]
>>> aList
[123, 'xyz', 456000000.0]

These in-place operators have equivalent special method names when creating classes to emulate numeric types. To implement an in-place special method, just add an “i” in front of the not-in-place operator; e.g., implement __iadd__() for the += operator as opposed to __add__() for just the + operator.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset