There are two ways to increment a variable in Python: a = a + b or a += b. Although the two methods can get the same result, they are not completely equivalent.
Addition operator+
For the statement a = a + b, we actually perform two steps, first a + b to find the sum of the two, and then assign the result to the variable A via the assignment operator =.
Consider the following example:
>>> a = 100
>>> b = 200
>>> id(a)
1796532544
>>> a = a + b
>>> a
300
>>> id(a)
17756816
Copy the code
>>> a = [11.22.33]
>>> b = [44.55.66]
>>> id(a)
54675856
>>> a = a + b
>>> a
[11.22.33.44.55.66]
>>> id(a)
54676416
Copy the code
A = a + b = a + b = a + b = a + b = a + b Note Variable A points to a new memory address after executing a = a + b. And that makes sense, because a has already been reassigned.
The incremental assignment operator+ =
The += operator is usually called the incremental assignment operator because it does both the addition and the assignment.
Again, we’ll use the int and list data types separately:
>>> a = 100
>>> b = 200
>>> id(a)
1796532544
>>> a += b
>>> a
300
>>> id(a)
17756784
Copy the code
>>> a = [11.22.33]
>>> b = [44.55.66]
>>> id(a)
48777616
>>> a += b
>>> a
[11.22.33.44.55.66]
>>> id(a)
48777616
Copy the code
For immutable type operations, a += b behaves the same as a = a + b. The same is not true for mutable types. Although variable A ends up with the same value, the memory address of variable A does not change after the += operation, which means that the += operation actually changes in place for mutable types. For list operations, actually a += b is equivalent to a.xtend (b).
__add__
和 __iadd__
methods
In fact, in Python, the addition operator + corresponds to an object’s __add__ method, and the incremental assignment operator += corresponds to an object’s __iadd__ method.
For both immutable and mutable types, a’s __add__ method is called when a = a + b is executed. For a += b operations, a’s __add__ method is also called when a is immutable, and a’s __iadd__ method is called when a is mutable. If a does not implement __iadd__, Then a’s __add__ method is called.
We can verify this statement with Python’s built-in Hasattr function.
>>> hasattr(int.'__add__')
True
>>> hasattr(int.'__iadd__')
False
>>> hasattr(list.'__add__')
True
>>> hasattr(list.'__iadd__')
True
Copy the code
For immutable types, there is no __iadd__ method because the objects themselves are immutable and adding them will inevitably create new objects. For mutable types, the object itself is mutable, so the __iadd__ method is implemented.
If we need to implement the above two methods in our own defined types, we should also follow the existing Python specification, be aware that the type of our implementation is mutable, and then determine whether we need to implement the __iadd__ method.