The Python + =

 

Lead to

Today wrote a Python script before running, there was a strange phenomenon (how old I encountered a strange phenomenon ~ ~). The code was probably a long way:

= A [. 1, 2,. 3 ] 
B = [. 4,. 5,. 6 ]
 # ... a large section of the logic 
C = A 
C + = B
 # ... a large segment logic 
# here, a becomes [ 1, 2, 3, 4, 5, 6]

First, the above code a function too long, and it is outrageous

This is the scene at the time, did not want the program to run as I expected. I'm looking for a long time, we did not find the changes to a variable or assignment.

In the end, they found hidden in the middle of the c variable, because the reference assignment is a list of objects, so directly modify a variable. I will address two variables printed out, is indeed the case.

Originally, I found here basically solve the case. We should not follow the

But I checked the Internet a bit, it was said with a = + does not happen, I contemptuous laugh, what is the difference? Nothing and I tried it.

What? Can anyone tell me what happened?

Probe

According to my guess, + = operator must be changed is the original object, = + operator returns a new object. try it:

as expected. In this detection.

Doubts

Know Python operator overloading operation is invoked addition __add__method, + = is called __iadd__a method. Now that produce this phenomenon, it must be listthe achievement of two slightly different methods.

Try to test yourself, write a Testclass that implements two overloaded methods:

Respectively call +=and =+:

You can see, it is a new value. If you modify the method of implementation:

再测试就会发下,两个运算返回的都是同一个对象。水落石出,Python对两个不同的运算符使用了不同的实现方法。

一探究竟

那为什么Python会在 +=操作时,直接修改原对象。而=+操作却要返回新的对象呢?

简单推测一下,可能Python的作者认为,+=操作是要将后边的值加到自身上。而+则是两个值的运算操作。根据表达是也可以看出:

a += b # 这里只涉及两个变量,将b的内容直接加到a上
c = a + b # 这里涉及到了三个变量,将后两者内容相加后赋值给新的变量

 


最后,既然+==+的实现不同,那么同理列表的-==-*==*/==/的实现也必然不同。

哦,不好意思,list没有实现减法和除法的操作。但乘法确实也是这样。

好吧,之后再进行对象运算符重载时可以参考一下上面的做法,仔细想想还是很合乎逻辑的。

Guess you like

Origin www.cnblogs.com/hujingnb/p/12037636.html