i = i+1 和 i += 1

时间:2020-03-15 17:36:55   收藏:0   阅读:50

i = i+1 和 i += 1

由于本身是不可变数据类型,执行后都会生产新的对象
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
可以看到 使用 += 并不会改变对象的内存地址
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黑洞网,博客园同步跟新

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

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!