python中a=a+1與a+=1的區別

一、a=a+2,表示一個新的對象,新的對象名字仍是a,可是指向的內存地址已經變了python

複製代碼
>>> a=2
>>> id(a)
140406287260016
>>> a=a+2
>>> a
4
>>> id(a)
140406287259968
複製代碼

因此對於tuple對象(不可變對象),也是能夠這樣操做的app

複製代碼
>>> tuple1=(1,2)
>>> id(tuple1)
4521580448
>>> tuple1=tuple1+(3,)
>>> tuple1
(1, 2, 3)
>>> id(tuple1)
4521658880
複製代碼

二、a+=2對於有些對象的操做是表示原來的對象,對有些對象的操做是生成了一個新對象函數

複製代碼
不可變對象tuple1,操做完後,內存地址已經發生變化,生成一個新的對象
>>> tuple1=(1,2) >>> type(tuple1) <type 'tuple'> >>> tuple1+=(3,) >>> id(tuple1) 4521658880 >>> tuple1+=(4,5) >>> id(tuple1) 4520649072
複製代碼

而list對象,可變對象,+=操做、append操做、extend操做,都是在原對象上操做spa

複製代碼
>>> list1=[1,2]
>>> id(list1)
4521614656
>>> list1+=[3]
>>> id(list1)
4521614656
>>> list1.append(4)
>>> id(list1)
4521614656
>>> list1.extend(5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> list1.extend([5])
>>> id(list1)
4521614656
>>>
複製代碼

三、code

複製代碼
x = [1,2,3]  
print "before func(), global! x = ",x,"id(x) = ",id(x)  
  
def func():  
    global x  
    print "in func(), local! original x = ",x,"id(x) = ",id(x)  
    x = x + [1]  
    print "in func(), local! now x = ",x,"id(x) = ",id(x)  
  
func()  
print "after func(), global! x = ",x,"id(x) = ",id(x)  
結果:
[python] view plain copy
before func(), global! x =  [1, 2, 3] id(x) =  47781768  
in func(), local! original x =  [1, 2, 3] id(x) =  47781768  
in func(), local! now x =  [1, 2, 3, 1] id(x) =  47795720  
after func(), global! x =  [1, 2, 3, 1] id(x) =  47795720  

global就保證了,即便個人變量x在函數中指向對象變了,外部的x也會指向新的對象
複製代碼

 

複製代碼
x = [1,2,3]  
print "before func(), global! x = ",x,"id(x) = ",id(x)  
  
def func(x):  
    print "in func(), local! original x = ",x,"id(x) = ",id(x)  
    x  = x + [1]  
    print "in func(), local! now x = ",x,"id(x) = ",id(x)  
  
func(x)  
print "after func(), global! x = ",x,"id(x) = ",id(x)  
結果:
before func(), global! x =  [1, 2, 3] id(x) =  46339976  
in func(), local! original x =  [1, 2, 3] id(x) =  46339976  
in func(), local! now x =  [1, 2, 3, 1] id(x) =  46390664  
after func(), global! x =  [1, 2, 3] id(x) =  46339976  

x = x + [1],是新建了一個對象,id(x) =  46390664
複製代碼

 

複製代碼
利用id(x),查看下x += [1]對象是怎麼變化的吧:
x = [1,2,3]  
print "before func(), global! x = ",x,"id(x) = ",id(x)  
  
def func(x):  
    print "in func(), local! original x = ",x,"id(x) = ",id(x)  
    x += [1]  
    print "in func(), local! now x = ",x,"id(x) = ",id(x)  
  
func(x)  
print "after func(), global! x = ",x,"id(x) = ",id(x)  
結果:
before func(), global! x =  [1, 2, 3] id(x) =  46536584  
in func(), local! original x =  [1, 2, 3] id(x) =  46536584  
in func(), local! now x =  [1, 2, 3, 1] id(x) =  46536584  
after func(), global! x =  [1, 2, 3, 1] id(x) =  46536584  id(x)全程同樣,x += [1],python直接就在原對象上操做
相關文章
相關標籤/搜索