id()
函数可以查看一个变量在内存中的地址对于以下代码
>>> import copy
>>> a=[1,2,3]
>>> b=a
>>> id(a)
"""
4382960392
"""
>>> id(b)
"""
4382960392
"""
>>> id(a)==id(b) #附值后,两者的id相同,为true。
True
>>> b[0]=222222 #此时,改变b的第一个值,也会导致a值改变。
>>> print(a,b)
[222222, 2, 3] [222222, 2, 3] #a,b值同时改变
id(a)==id(b)
。 通过改变b的元素也可以起到改变a中元素的作用,同理,改变a中的元素也会改变b中的元素。可变对象是指,一个对象在不改变其所指向的地址的前提下,可以修改其所指向的地址中的值; 值和地址不对应(列表)
不可变对象是指,一个对象所指向的地址上值是不能修改的,如果你修改了这个对象的值,那么它指向的地址就改变了 值和地址相互对应(int,float,complex,long,str,unicode,tuple) , 元组 tuple就属于不可变对象
a_list = [1, 2, 3]
a_shallow_list = copy.copy(a_list)
a_deep_list = copy.deepcopy(a_list)
print("id of a_list", id(a_list), "id of a_shallow_list", id(a_shallow_list), "a_deep_list", id(a_deep_list))
# id of a_list 2249250705672 id of a_shallow_list 2249201900552 a_deep_list 2249201900424
int
类型,是不可变对象,因此其只要其中数值不变地址也不会变化。print("id of a_list[0]", id(a_list[0]), "id of a_shallow_list[0]", id(a_shallow_list[0]), "a_deep_list[0]", id(a_deep_list[0]))
# id of a_list[0] 1887096560 id of a_shallow_list[0] 1887096560 a_deep_list[0] 1887096560
# 基本可变对象中不可变对象的地址不会改变
a_tuple = (1, 2, 3)
a_shallow_tuple = copy.copy(a_tuple)
a_deep_tuple = copy.deepcopy(a_tuple)
# 比较基本不可变对象,深复制和浅复制区别
print("id of a_tuple", id(a_tuple), "a_shallow_tuple", id(a_shallow_tuple), "a_deep_tuple", id(a_deep_tuple))
print("id of a_tuple[0]", id(a_tuple[0]), "a_shallow_tuple[0]", id(a_shallow_tuple[0]), "a_deep_tuple[0]",
id(a_deep_tuple[0]))
# id of a_tuple 2344837083280 a_shallow_tuple 2344837083280 a_deep_tuple 2344837083280
# id of a_tuple[0] 1885130480 a_shallow_tuple[0] 1885130480 a_deep_tuple[0] 1885130480
a1_tuple = (1, 2, (1, 2, 3), [1, 2, 3])
a1_shallow_tuple = copy.copy(a1_tuple)
a1_deep_tuple = copy.deepcopy(a1_tuple)
# 复合嵌套不可变元素的深复制和浅复制区别
print("id of a1_tuple", id(a1_tuple), "a1_shallow_tuple", id(a1_shallow_tuple), "a1_deep_tuple", id(a1_deep_tuple))
print("id of a1_tuple[3]", id(a1_tuple[3]), "a1_shallow_tuple[3]", id(a1_shallow_tuple[3]), "a1_deep_tuple[3]",
id(a1_deep_tuple[3]))
# id of a1_tuple 2498218636296 a1_shallow_tuple 2498218636296 a1_deep_tuple 2498218638776
# id of a1_tuple[3] 2498267415048 a1_shallow_tuple[3] 2498267415048 a1_deep_tuple[3] 2498218716040
a1_list = [1, 2, (1, 2, 3), [1, 2, 3]]
a1_shallow_list = copy.copy(a1_list)
a1_deep_list = copy.deepcopy(a1_list)
# 复合嵌套可变元素的深复制和浅复制区别
print("id of a1_list", id(a1_list), "id of a1_shallow_list", id(a1_shallow_list), "a1_deep_list", id(a1_deep_list))
print("id of a1_list[3]", id(a1_list[3]), "id of a1_shallow_list[3]", id(a1_shallow_list[3]), "a1_deep_list[3]",
id(a1_deep_list[3]))
# id of a1_list 1453555407752 id of a1_shallow_list 1453555447432 a1_deep_list 1453555477384
# id of a1_list[3] 1453604277640 id of a1_shallow_list[3] 1453604277640 a1_deep_list[3] 1453555448968
原文:https://www.cnblogs.com/cloud-ken/p/12638393.html