今天看python过程中遇到一个问题,比较疑惑。
元组aee = (1,2,3), 执行aee += ()后, id改变为值A。再执行aee += (), id改变为值B, 再执行aee += (), id又变为值A。 继续执行,id在A和B之间切换。 这是为什么?
先上代码:
def test():
aee = (1,2,3)
print ("1:", aee)
print ("id_1:", id(aee))
aee += ()
print ("2:", aee)
print ("id_2:", id(aee))
aee += ()
print ("3:", aee)
print ("id_3:", id(aee))
aee += ()
print ("4:", aee)
print ("id_4:", id(aee))
aee += ()
print ("5:", aee)
print ("id_5:", id(aee))
if __name__ == "__main__":
test()
运行结果:
λ python3 C:\Users\qingfang\Desktop\test20180628.py
1: (1, 2, 3)
id_1: 2554181486200
2: (1, 2, 3)
id_2: 2554181486344 # id A
3: (1, 2, 3)
id_3: 2554181417648 # id B
4: (1, 2, 3)
id_4: 2554181486344 # id A
5: (1, 2, 3)
id_5: 2554181417648 # id B
中间添加一个元组,查看id是否有改变?
def test():
aee = (1,2,3)
print ("1:", aee)
print ("id_1:", id(aee))
aee += ()
print ("2:", aee)
print ("id_2:", id(aee))
aee += ()
print ("3:", aee)
print ("id_3:", id(aee))
abb = (2,3,4) #测试代码
print ("abb:", abb)
print ("id_abb:", id(abb))
aee += ()
print ("4:", aee)
print ("id_4:", id(aee))
aee += ()
print ("5:", aee)
print ("id_5:", id(aee))
if __name__ == "__main__":
test()
运行结果:
λ python3 C:\Users\qingfang\Desktop\test20180628.py
1: (1, 2, 3)
id_1: 2760120043128
2: (1, 2, 3)
id_2: 2760119974576 # id A
3: (1, 2, 3)
id_3: 2760120076832 # id B
abb: (2, 3, 4)
id_abb: 2760120043272 # 添加的变量 Id
4: (1, 2, 3)
id_4: 2760119974576 # id A
5: (1, 2, 3)
id_5: 2760120076832 # id B
还是相同的。