1、淺拷貝
(1)定義
淺拷貝是指重新配置設定一份記憶體空間給新變量,新變量的元素是原變量的的元素的引用。
(2)實作方式
1)通過類型構造器
l1 = [1, 2, 3]
l2 = list(l1)
print l1 == l2 # True
print l1 is l2 # False
s1 = (1, 2, 3)
s2 = set(s1)
print s1 == s2 # True
print s1 is s2 # False
l1 = [[1, 2], (3, 4), 5]
l2 = list(l1)
print l1==l2 # True
print l1 is l2 # False
print l1[0] is l2[0] # True
print l1[1] is l2[1] # True
# 注意可變變量list和不可變變量set的差別
l1[0].append(3)
print l1 # [[1, 2, 3], (3, 4), 5]
print l2 # [[1, 2, 3], (3, 4), 5]
l1[1].append(5)
print l1 # [[1, 2, 3], (3, 4, 5), 5]
print l2 # [[1, 2, 3], (3, 4), 5]
2)通過切片操作,對清單來說,
l1 = [1, 2, 3]
l2 = l1[:]
print l1 == l2 # True
print l1 is l2 # False
s1 = (1, 2, 3)
s2 = s1[:]
print s1 == s2 # True
print s1 is s2 # False
3)通過copy 子產品的copy方法
import copy
l1 = [1, 2, 3]
l2 = copy.copy(l1)
print l1 == l2 # True
print l1 is l2 # False
s1 = (1, 2, 3)
s2 = copy.copy(s1)
print s1 == s2 # True
print s1 is s2 # False
2、深拷貝
(1)定義
深拷貝是指重新配置設定一份記憶體空間給新變量,并以遞歸的方式将原變量的元素重新拷貝一份到新變量中,是以新變量中儲存的是全新的元素,不再是原變量元素的引用,是以原變量與新變量沒有任何聯系,原變量做的任何修改也不會同步到新變量中。
(2)實作方式
1)通過copy子產品的deepcopy方法
import copy
l1 = [1, 2, 3]
l2 = copy.deepcopy(l1)
print l1 == l2 # True
print l1 is l2 # False
l1 = [[1, 2], (3, 4), 5]
l2 = copy.deepcopy(l1)
print l1==l2 # True
print l1 is l2 # False
print l1[0] is l2[0] # False
print l1[1] is l2[1] # False
l1[0].append(3)
print l1 # [[1, 2, 3], (3, 4), 5]
print l2 # [[1, 2], (3, 4), 5]
l1[1].append(5)
print l1 # [[1, 2, 3], (3, 4, 5), 5]
print l2 # [[1, 2], (3, 4), 5]
3、"==" 和 "is"的差別
(1)"==" 判斷的是對象的值是否相等
(2)"is" 判斷的是對象的位址是否相等,即通過 id(object)獲得的身份辨別。
4、"=" 指派運算符
l1 = [1, 2, 3]
l2 = l1
print l1 is l2 # True,此時 l1和l2指向同一個位址,在這個位址上做的任何改變都會更新到l1,l2