理解符合赋值运算 a += a 与 a = a + a 是不一样的
In [22]: a = [100] In [23]: id(a) Out[23]: 140100796244928 In [24]: def test1(a): ...: a = a + a #这里先计算的等号右边,a + a 即 [100] + [100] 结果为 [100,100], 然后等号左边a使用新的 引用指向 [100,100] ...: _id = id(a) ...: print(a,_id) ...: test1(a) [100, 100] 140100794569472 #函数中的a的引用地址 已经不是外部a的引用地址了 In [25]: a #整个过程 a 未被改变 ! Out[25]: [100] In [26]: id(a) Out[26]: 140100796244928 #外部的 a 空间地址没有被改变 In [28]: def test2(a): ...: a += a # =a 将等号右边 指向 [100] 然后进行运算 即在a的引用指向的位置 进行修改 ...: _id = id(a) ...: print(a,_id) ...: test2(a) [100, 100] 140100796244928 #函数中a的地址就是 外部变量a的地址 ,即直接对外部a进行修改了 In [29]: a Out[29]: [100, 100] #外部a 已经被修改! 因为函数内的a引用 和 外部a引用是同一个 In [30]: id(a) Out[30]: 140100796244928