# python小白 问关于a+=a 和a=a+a的区别

wutianlong220 2017年06月12日提问
1

``````# -*- coding:gb2312 -*-

a = [100]

def test(num):
num += num #第一段代码
print(num)

test(a)
print(a)``````

``````# -*- coding:gb2312 -*-

a = [100]

def test(num):
num = num + num  #这个地方改了一下
print(num)

test(a)
print(a)``````

num += num不应该直接等价于mun = num+num 么

## 4个回答

1

2

``````In [1]: a = [100]

In [2]: b = [100]

In [3]: id(a)
Out[3]: 79308552L

In [4]: id(b)
Out[4]: 79342728L

In [5]: a += a

In [6]: b = b + b

In [7]: id(a)
Out[7]: 79308552L

In [8]: id(b)
Out[8]: 79341192L``````

``````In [19]: a = (0,)

In [20]: b = (0,)

In [21]: id(a)
Out[21]: 82230688L

In [22]: id(b)
Out[22]: 82208920L

In [23]: a += a

In [24]: b = b + b

In [25]: id(a)
Out[25]: 79268296L

In [26]: id(b)
Out[26]: 79328392L``````

+表示连接操作，+=表示追加

2

``````In [26]: def test(num):
...:     num = num + num
...:     print (num)
...:

In [27]: def test1(num):
...:     num += num
...:     print (num)
...:

In [28]: import dis

In [29]: dis.dis(test)
2           0 LOAD_FAST                0 (num)
3 LOAD_FAST                0 (num)
7 STORE_FAST               0 (num)

3          10 LOAD_FAST                0 (num)
13 PRINT_ITEM
14 PRINT_NEWLINE
15 LOAD_CONST               0 (None)
18 RETURN_VALUE

In [30]: dis.dis(test1)
2           0 LOAD_FAST                0 (num)
3 LOAD_FAST                0 (num)
7 STORE_FAST               0 (num)

3          10 LOAD_FAST                0 (num)
13 PRINT_ITEM
14 PRINT_NEWLINE
15 LOAD_CONST               0 (None)
18 RETURN_VALUE
``````

0

``````a = [100]

def test(num):
num = num + num  #这个地方改了一下
return(num)      #这个地方再改了一下

print(test(a))       #傳值回來
print(a)
a = test(a)
print(a)
``````

``````[100, 100]
[100]
[100, 100]
``````