強化訓練:第六篇
1. 深淺拷貝:是否是同一個對象,使用id判斷是否指向同一個對象, 深淺拷貝董虱,引用區(qū)分可變對象和不可變對象
# 賦值法創(chuàng)建引用, 指向同一對象, id值相同
foo1 = 3
foo2 = foo1
print("id = ", id(foo1), "id = ", id(foo2))
#id = 1493167984 id = 1493167984
foo1 = 4
print(foo2, foo1)
#3 4
# 整型不可變對象, python 會緩存數(shù)據(jù)
foo3 = 3
foo4 = 2 + 1
print("id = ", id(foo3), "id = ", id(foo4))
#id = 1493167984 id = 1493167984
# python 僅緩存簡單整型
foo5 = 3.14
foo6 = 2.14 + 1
foo7 = foo5
print("id = ", id(foo5), "id = ", id(foo6), "id = ", id(foo7))
#id = 3449480 id = 3449504 id = 3449480
# 可變對象, 引用, 淺拷貝影響源數(shù)據(jù), 深拷貝指向不同對象
## 引用
list_one = [1, 2, 3]
list_two = list_one
print("id = ", id(list_one), "id = ", id(list_two))
# id = 12186120 id = 12186120
list_one[2] = 4
print(list_two)
#[1, 2, 4]
list_two[1] = 5
print(list_one)
print("id = ", id(list_one), "id = ", id(list_two))
#[1, 5, 4]
#id = 12186120 id = 12186120
## 深淺拷貝
from copy import copy, deepcopy
list_three = [1, 2, [3, 4]]
list_four = list_three # 引用:指向相同對象
list_five = copy(list_three) # 淺拷貝
list_six = deepcopy(list_three) # 深拷貝
print(id(list_three), id(list_four), id(list_five), id(list_six))
#12185736 12185736 12321864 12127880
list_four[1] = 1156143589
print("list_three= ", list_three, "list_five= ", list_five, "list_six= ", list_six)
# list_three= [1, 1156143589, [3, 4]] list_five= [1, 2, [3, 4]] list_six= [1, 2, [3, 4]]
list_three[0] = 88688
print("list_four= ", list_four, "list_five= ", list_five, "list_six= ", list_six)
#list_four= [88688, 1156143589, [3, 4]] list_five= [1, 2, [3, 4]] list_six= [1, 2, [3, 4]]
list_five[0] = 4444
print("list_three= ", list_three, "list_four= ", list_four)
# list_three= [88688, 1156143589, [3, 4]] list_four= [88688, 1156143589, [3, 4]]
list_five[2][1] = 666666
print("list_three= ", list_three, "list_four= ", list_four, "list_six= ", list_six)
#list_three= [88688, 1156143589, [3, 666666]] list_four= [88688, 1156143589, [3, 666666]] list_six= [1, 2, [3, 4]]
list_six[2][0] = 99999
print("list_three= ", list_three, "list_four= ", list_four, "list_five= ", list_five, "list_six= ", list_six)
#list_three= [88688, 1156143589, [3, 666666]] list_four= [88688, 1156143589, [3, 666666]] list_five= [4444, 2, [3, 666666]] list_six= [1, 2, [99999, 4]]
2. 總結(jié)
- 引用指向同一對象:相同id, 不可變對象獨立操作,可變對象相互影響
- 淺拷貝:只拷貝父對象申鱼, 嵌套可變對象會影響數(shù)據(jù)源
- 深拷貝還會拷貝對象的內(nèi)部的子對象:獨立操作愤诱,不影響數(shù)據(jù)源