1.深拷贝和浅拷贝
1.1、基本概念
浅拷贝(shallow copy ):拷贝父对象,不会拷贝对象的内部子对象
A shallow copy creates a new object which stores the reference of the original elements.So, a shallow copy doesn’t create a copy of nested objects, instead it just copies the reference of nested objects. This means, a copy process does not recurse or create copies of nested objects itself.
深拷贝(deepcopy ):完全拷贝父对象及其子对象
A deep copy creates a new object and recursively adds the copies of nested objects present in the original elements.
直接赋值:对象的引用
1.2、参考代码说明:
# 深拷贝和浅拷贝的对应过程
import copy
test1 = [1, 2, 3, 4, ['a', 'b']]
test2 = test1 # 原始赋值
copy_test = copy.copy(test1) # 浅拷贝
deepcopy_test = copy.deepcopy(test1) # 深拷贝
# 修改对象
test1.append(5)
# 修改对象内层嵌套的列表
test1[4].append('c')
print("原始对象test1%s" % test1)
print("直接赋值test2%s" % test2)
print("这是浅拷贝的值%s" % copy_test)
print("这是深拷贝的值%s" % deepcopy_test)
# 原始对象test1[1, 2, 3, 4, ['a', 'b', 'c'], 5]
# 直接赋值test2[1, 2, 3, 4, ['a', 'b', 'c'], 5]
# 这是浅拷贝的值[1, 2, 3, 4, ['a', 'b', 'c']]
# 这是深拷贝的值[1, 2, 3, 4, ['a', 'b']]
# 针对深浅拷贝的进一步详解:
# 创建一个浅拷贝
old_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new_list = copy.copy(old_list)
print("Old list:", old_list)
print("New list:", new_list)
# Old list: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# New list: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# 像原始列表中添加元素查看浅拷贝的变化
old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_list = copy.copy(old_list)
old_list.append([4, 4, 4])
print("Old list:", old_list) # Old list: [[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]]
print("New list:", new_list) # New list: [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
# 修改嵌套列表中的值
old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_list = copy.copy(old_list)
old_list[1][1] = 'AA'
print("Old list:", old_list)
print("New list:", new_list)
# Old list: [[1, 1, 1], [2, 'AA', 2], [3, 3, 3]]
# New list: [[1, 1, 1], [2, 'AA', 2], [3, 3, 3]]
import copy
# 创建一个深拷贝
old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_list = copy.deepcopy(old_list)
print("Old list:", old_list)
print("New list:", new_list)
# Old list: [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
# New list: [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
# 添加一个新嵌套
old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_list = copy.deepcopy(old_list)
old_list[1][0] = 'BB'
print("Old list:", old_list)
print("New list:", new_list)
# Old list: [[1, 1, 1], ['BB', 2, 2], [3, 3, 3]]
# New list: [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
1.3、解析
1.3.1 直接赋值中, test1 and test2 都是指向同一个对象
1.3.2 浅拷贝, test1 and copy_test 是一个独立对象,但是他们的子对象还是指向统一对象,因此浅拷贝copy_test并没有修改外层值,与之变化的为内层子对象的值发生变化
1.3.3 深拷贝, test1 and deepcopy_test 完全拷贝了父对象及其子对象,两个是相互独立的。因此,在更改test1父对象和子对象值以后,deepcopy_test值不会发生变化
参考链接:
https://www.runoob.com/w3cnote/python-understanding-dict-copy-shallow-or-deep.html
http://www.programiz.com/python-programming/shallow-deep-copy