python中a与a_python中a=a+2与a+=2的区别

1、a=a+2,表示一个新的对象,新的对象名字还是a,但是指向的内存地址已经变了

>>> a=2

>>> id(a)

140406287260016

>>> a=a+2

>>> a

4

>>> id(a)

140406287259968

所以对于tuple对象(不可变对象),也是可以这样操作的

>>> tuple1=(1,2)

>>> id(tuple1)

4521580448

>>> tuple1=tuple1+(3,)

>>> tuple1

(1, 2, 3)

>>> id(tuple1)

4521658880

2、a+=2对于有些对象的操作是表示原来的对象,对有些对象的操作是生成了一个新对象

不可变对象tuple1,操作完后,内存地址已经发生变化,生成一个新的对象

>>> tuple1=(1,2)

>>> type(tuple1)

>>> tuple1+=(3,)

>>> id(tuple1)

4521658880

>>> tuple1+=(4,5)

>>> id(tuple1)

4520649072

而list对象,可变对象,+=操作、append操作、extend操作,都是在原对象上操作

>>> 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 "", line 1, in

TypeError: 'int' object is not iterable

>>> list1.extend([5])

>>> id(list1)

4521614656

>>>

3、

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直接就在原对象上操作

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值