Is the result of a += b and a = a + b different in Python?

Python combat community

Java combat community

Long press to identify the QR code below, add as required

Scan QR code to follow to add customer service

Enter the Python community▲

Scan QR code to follow to add customer service

Enter the Java community

Source丨Data Analysis and Python

Mutable and immutable types

Want to know if the results of a += b and a = a + b are the same. We must first know what is variable and unvariable.

Python

  • Immutable types: numbers, strings, tuples

  • Variable types: list, dictionary

Examples of immutable type operations

    1. Immutable +=

    2. Immutable = +

The result of immutable type after += and =+ is the same.


Examples of Variable Type Operations

     1. Variable +=

Variable type += situation

2. Variable = +

Variable type a=a+b case

Through the comparison of the above figure, we find that the results of variable type variables are different when performing a += b and a = a + b. In the += operation, the values ​​of a1 and a2 change at the same time, but a1 and a2 cannot be changed at the same time when the value is added first and then assigned.

Everyone must remember the above conclusion

The difference between __add__ and __iadd__

  • The __add__ method receives two parameters, returns their sum, and the values ​​of the two parameters remain unchanged.

  • The __iadd__ method receives two parameters, the value of the first parameter changes

The variable type uses the plus operation (ie a=a+b), calling __add__ will return a new object, and the original object remains unchanged.

The schematic diagram is as follows:

After a1 = a1 + b, a1 will point to the new result, but a2 will point to the same

The variable type uses the += operation (ie a+=b) to call the __iadd__ method, and the value of the first parameter changes, that is, the content of the a1 pointed to by itself changes, but the pointing position does not change.

The schematic diagram is as follows:

After a1 += b, the content pointed to by a1 changes, and the pointed position does not change, so the content of a2 will also change along with a1

程序员专栏 扫码关注填加客服 长按识别下方二维码进群

Recommended recent exciting content:  

 Comparison of programmer income in China, the United States, Japan and India

 A sad day for programmers

 SringMVC from entry to source code, this one is enough

 10 Python visual animations, carefully and beautifully


Watch the good article here to share it with more people↓↓

Guess you like

Origin blog.csdn.net/Px01Ih8/article/details/109301892