流畅的python学习笔记-第8章

第8章-对象引用、可变性和垃圾回收

[toc]

浅拷贝

copy 浅复制,不会拷贝其子对象,修改子对象,将受影响

import copy
a = [1, 2, 3]
b = copy.copy(a)

print("id a=", id(a))  # id a= 1669348705224
print("id b=", id(b))  # id b= 1669348161608

print("id a 0=", id(a[0]))  # id a 0= 1586588704
print("id b 0=", id(b[0]))  # id b 0= 1586588704

a[0] = "hello"
print("new a=", a)  # new a= ['hello', 2, 3]
print("new b=", b)  # new b= [1, 2, 3]

b[0] = "world"
print("new 2 a=", a)  # new a= ['hello', 2, 3]
print("new 2 b=", b)  # new 2 b= ['world', 2, 3]


深拷贝

deepcopy 深复制,将拷贝其子对象,修改子对象,将不受影响

import copy
a = [1, 2, 3]
b = copy.deepcopy(a)

print("id a=", id(a))  # id a= 2760920581064
print("id b=", id(b))  # id b= 2760920037448

print("id a 0=", id(a[0]))  # id a 0= 1586588704
print("id b 0=", id(b[0]))  # id b 0= 1586588704

a[0] = "hello"
print("new a=", a)  # new a= ['hello', 2, 3]
print("new b=", b)  # new b= [1, 2, 3]

b[0] = "world"
print("new 2 a=", a)  # new a= ['hello', 2, 3]
print("new 2 b=", b)  # new 2 b= ['world', 2, 3]

两者区别

发现对于不可变对象,比如整数、字符串、元组、还有由这些不可变对象组成的集合对象,浅拷贝和深拷贝没有区别,都是拷贝一个新对象

两者的区别在于拷贝组合对象,比如列表中还有列表,字典中还有字典或者列表的情况时,浅拷贝只拷贝了外面的壳子,里面的元素并没有拷贝,而深拷贝则是把壳子和里面的元素都拷贝了一份新的。

看一个例子:

import copy

a = [0, [1, 2], 3]
b = copy.copy(a)
c = copy.deepcopy(a)

c[1][0] = "hello"
print("a=", a)  # a= [0, [1, 2], 3]
print("c=", c)  # c= [0, ['hello', 2], 3]

b[1][0] = "world"

print("new a=", a)  # new a= [0, ['world', 2], 3]
print("new b=", b)  # new b= [0, ['world', 2], 3]


小提示:

可以利用 python在线调试进行相关调试分析

你可能感兴趣的:(python)