python中的深拷貝和淺拷貝

2021-10-02 16:21:53 字數 2878 閱讀 2789

copy.copy()中如果拷貝的是列表等可修改物件,則會拷貝最上一層,如果拷貝的最上層是元組等不可修改物件,則只是拷貝了物件的引用:

in [2]: a = [1, 2, 3]

in [3]: b = copy.copy(a)

in [4]: id(a)

out[4]: 140568059574600

in [5]: id(b)

out[5]: 140568059649992

in [6]: a = (1, 2, 3)

in [7]: b = copy.copy(a)

in [8]: id(a)

out[8]: 140568101534096

in [9]: id(b)

out[9]: 140568101534096

copy.deepcopy()中如果拷貝的是不可變物件,依然是拷貝物件的引用:

in [2]: a = (1, 2, 3)

in [3]: b = copy.deepcopy(a)

in [4]: id(a)

out[4]: 140313481712336

in [5]: id(b)

out[5]: 140313481712336

而如果巢狀內部包含可修改和不可修改物件,則會逐級拷貝所有的可修改物件並只拷貝所有的不可修改物件的引用:

in [6]: a = [1, 3]

in [7]: b = (2, 4)

in [8]: c = [a, b]

in [9]: d = copy.deepcopy(c)

in [10]: id(c)

out[10]: 140313510332424

in [11]: id(d)

out[11]: 140313468881672

in [12]: id(c[1])

out[12]: 140313468353096

in [13]: id(d[1])

out[13]: 140313468353096

in [14]: id(c[0])

out[14]: 140313468365640

in [15]: id(d[0])

out[15]: 140313468161608

如果內層包含有可修改物件,則無論外層為可修改物件還是不可修改物件,對外層物件都會進行拷貝,而不是僅對外層物件的引用進行拷貝:

in [16]: a = [1, 3]

in [17]: b = (2, 4)

in [18]: c = (a, b)

in [19]: d = copy.deepcopy(c)

in [20]: id(c)

out[20]: 140313510401352

in [21]: id(d)

out[21]: 140313482148872

in [22]: id(c[0])

out[22]: 140313482149192

in [23]: id(d[0])

out[23]: 140313468180744

in [24]: id(c[1])

out[24]: 140313479821256

in [25]: id(d[1])

out[25]: 140313479821256

in [26]: e = (c, (1, 3))

in [27]: f = copy.deepcopy(e)

in [28]: id(e)

out[28]: 140313510249160

in [29]: id(f)

out[29]: 140313468328072

in [30]: id(e[0])

out[30]: 140313510401352

in [31]: id(f[0])

out[31]: 140313479822280

in [32]: id(e[1])

out[32]: 140313510370888

in [33]: id(f[1])

out[33]: 140313510370888

切片也是淺拷貝的一種:

in [42]: a = (1, 3, 5)

in [43]: b = a[:]

in [44]: id(a)

out[44]: 140313506521160

in [45]: id(b)

out[45]: 140313506521160

in [46]: a = [1, 3, 5]

in [47]: b = a[:]

in [48]: id(a)

out[48]: 140313468221256

in [49]: id(b)

out[49]: 140313479813576

in [50]: id(a[0])

out[50]: 10914496

in [51]: id(b[0])

out[51]: 10914496

in [52]: a = [1, 3, [2, 4]]

in [53]: b = a[:]

in [54]: id(a)

out[54]: 140313510367816

in [55]: id(b)

out[55]: 140313468221256

in [56]: id(a[2])

out[56]: 140313479811016

in [57]: id(b[2])

out[57]: 140313479811016

python中的淺拷貝和深拷貝

不得不說 python核心程式設計 是一本好書,看到其中一節做一下隨筆。在python中,當建立乙個物件後,然後把它賦給另乙個物件時,python並沒有去拷貝這個物件,而是拷貝了這個物件的引用。看不懂沒關係,我們看乙個例子。raw list first second 12 32 copy list ...

python中的深拷貝和淺拷貝

淺拷貝 copy 不拷貝物件的內容,僅僅拷貝子物件的引用 深拷貝 deepcopy 會連同拷貝子物件的記憶體,對子物件的修改不會影響源物件 下面用 來測試 import copy deftest copy 淺拷貝測試 a 10 20,5,6 b copy.copy a print a a,end t...

python中的淺拷貝和深拷貝

本篇介紹下python中的深拷貝和淺拷貝,主要從基本型別 類 不可變型別等方面進行介紹。1.介紹拷貝之前首先應該明白is和 的區別,即is表示同乙個物件,比較的是值 a 1000 b 1000 a b true a is bfalse class person object def init sel...