python 爲 10 開闢內存空間, a與b同時指向這塊內存,即a與b的值相等,a與b的id也相等.所以 a==b 與 a is b 都返回True:html
a = 10 b = 10 print(a == b) #True print(id(a)) #140726165951808 print(id(b)) #140726165951808 print(a is b) #True
a = 257 b = 257 print(a == b) #True print(id(a)) #139636876096528 print(id(b)) #139636905893680 print(a is b) #False
t1 = (1, 2, [3, 4]) t2 = (1, 2, [3, 4]) print(t1 == t2) #True t1[-1].append(5) print(t1 == t2) #False
使用數據類型自己的構造器,是淺拷貝python
l1 = [1, 2, 3] l2 = list(l1) #l2 #[1, 2, 3] print(l1 == l2) #True print(l1 is l2) #False s1 = set([1, 2, 3]) s2 = set(s1) #s2 #{1, 2, 3} print(s1 == s2) #True print(s1 is s2) #False
切片也是淺拷貝性能優化
l1 = [1, 2, 3] l2 = l1[:] print(l1 == l2) #True print(l1 is l2) #False
copy.copy()淺拷貝app
import copy l1 = [1, 2, 3] l2 = copy.copy(l1) print(l1 is l2) #False
對於元組,這些操做都是返回指向同一元組(1,2,3)的引用性能
import copy t1 = (1, 2, 3) #t2 = tuple(t1) #t2 = t1[:] #t2 = copy.copy(t1) t2 = copy.deepcopy(t1) #若是元組中不僅是原子類型,好比有list,dict就能夠用deepcopy print(t1 == t2) #True print(t1 is t2) #True
如下代碼 l2 = list(l1)表示 l2 指向 l1淺拷貝生成的新對象, 而對象中的元素,淺拷貝就只會使用原始元素的引用(內存地址)優化
l1 = [[1, 2], (30, 40)]
l2 = list(l1)
因爲l1與l2是兩個指向不一樣的對象,因此 l1指向的列表增長元素不會改變 l2指向的列表spa
l1.append(100) print(l1) #[[1, 2, 3], (30, 40), 100] print(l2) #[[1, 2, 3], (30, 40)]
因爲淺拷貝對象中的元素是引用原始元素的內存地址,所以對於可變類型(list)增長了3,l2與l1中list的是同一個引用,所以也是[1,2,3]命令行
l1[0].append(3) print(l1) #[[1, 2, 3], (30, 40), 100] print(l2) #[[1, 2, 3], (30, 40)]
因爲 tuple是不可變類型,所以修改後l1指向從新分配的一個新元組的引用。code
l1[1] += (50, 60) print(l1) #[[1, 2, 3], (30, 40, 50, 60), 100] print(l2) #[[1, 2, 3], (30, 40)]
拷貝出來的新對象徹底獨立於原對象,修改操做與原對象互不影響htm
import copy x = [1] x.append(x) print(x) # [1, [...]] y = copy.deepcopy(x) print(y) # [1, [...]] print(x is y) #False print(x == y) #RecursionError: maximum recursion depth exceeded in comparison 遞歸錯誤
https://www.cnblogs.com/wilber2013/p/4645353.html
極客時間《Python 核心技術與實戰》專欄