首页 > 其他 > 详细

i = i+1 和 i += 1

时间:2020-03-15 17:36:55      阅读:50      评论:0      收藏:0      [点我收藏+]

i = i+1 和 i += 1

  • 对于不可变数据类型(str、int、tuple)
由于本身是不可变数据类型,执行后都会生产新的对象
x = 1
print(id(x))  # 1510566928
x += 1
print(id(x))  # 1510566960
---------------------------
x = 1
print(id(x))  # 1510566954
x = x + 1
print(id(x)) # # 1510566998
  • 可变数据类型情况(list、dict)
可以看到 使用 += 并不会改变对象的内存地址
x = [1, 2]
print(id(x))  # 2701823038387
x = x + [3, 4]
print(id(x))  # 2701823038334
------------------
x = [1, 2]
print(id(x))  # 2701823038344
x += [3, 4]
print(id(x))  # 2701823038344
  • 注意
n = n + n 作用域问题内部为[1, 2, 1, 2], 外部仍为[1, 2]
 
def num(n):
    n = n + n
x = [1, 2]
num(x)
print(x)  # [1, 2]
--------------------
def num(n):
    n += n
x = [1, 2]
num(x)
print(x)  # [1, 2, 1, 2]


本文首发于Python黑洞网,博客园同步跟新

i = i+1 和 i += 1

原文:https://www.cnblogs.com/pythonzhilian/p/12498477.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!