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直接就在原对象上操做
相关文章
相关标签/搜索