python跟java中的变量本质是不一样的,Python的变量实质上是一个指针(int型或str型),而java的变量是一个可操作的存储空间。
例1
a = 1
b = a
print(id(a), id(b)) # 2052450224 2052450224
a = 2 #不可变对象被重新赋值,重新分配了一块内存,ID就变了
print(a, b) # 2 1
print(id(a), id(b)) # 2052450240 2052450224
例2
列表直接赋值给列表不属于拷贝, 只是内存地址的引用
list1 = ["a", "b", "c"]
list2 = list1
list1.append("d")
print(list1, list2) # ['a', 'b', 'c', 'd'] ['a', 'b', 'c', 'd']
print(id(list1), id(list2)) # 1947385383176 1947385383176
例3
浅拷贝
list1 = ["a", "b", "c"]
list2 = list1.copy()
list3=list(list1) #转换也是浅copy
list1.append("d")
print(list1, list2,list3)
# ['a', 'b', 'c', 'd'] ['a', 'b', 'c'] ['a', 'b', 'c']
print(id(list1), id(list2),id(list3))
# 113196712 113196104 113196936
例4
浅拷贝, 只会拷贝第一层, 第二层的内容不会拷贝
list1 = ["a", "b", "c", [1, 2, 3]]
list2 = list1.copy()
list1[3].append(4)
print(list1, list2)
# ['a', 'b', 'c', [1, 2, 3, 4]] ['a', 'b', 'c', [1, 2, 3, 4]]
print(id(list1), id(list2))
# 1386655149640 1386655185672
例5
深拷贝
import copy
list1 = ["a", "b", "c", [1, 2, 3]]
list2 = copy.deepcopy(list1)
list1[3].append(4)
print(list1, list2)
# ['a', 'b', 'c', [1, 2, 3, 4]] ['a', 'b', 'c', [1, 2, 3]]
print(id(list1), id(list2))
# 1452762592904 1452762606664