深浅拷贝

本贴最后更新于 416 天前,其中的信息可能已经时移俗易

一、定义

1、浅拷贝:拷贝父对象,引用子对象

2、深拷贝:拷贝父对象和子对象

3、深拷贝只在嵌套的容器对象内使用才有意义

二、其他定义

1、容器:把所有能存东西的对象都叫做容器

2、父对象:嵌套在外层的容器叫父对象

2、子对象:嵌套在内存的容器叫子对象

如:test_dict2 = {"key1":"value1","key2":[1,2,3,4,5]}

第一层字典是父对象,第二层列表是子对象

三、可变或不可变容器

1、str类型是不可变容器

如:box = "python"

2、列表是可变容器

如:test_list = [1,2,3]

3、字典是可变容器

如:test_dict = {"key1":"value1","key2":"value2"}

四、浅拷贝

1、语法:拷贝对象.copy()

2、例子

【例1】

test_dict1 = {"key1":"value1","key2":"value2"}

print(test_dict1)

结果:{'key1': 'value1', 'key2': 'value2'}

test_dict2 = test_dict1.copy()

print(test_dict2)

结果:{'key1': 'value1', 'key2': 'value2'}

现在修改test_dict1,看test_dict2会不会修改:

test_dict1["key2"] = "test2"

print(test_dict1)

print(test_dict2)

结果:

{'key1': 'value1', 'key2': 'test2'}
{'key1': 'value1', 'key2': 'value2'}

可见,test_dict2没有变

【例2】

test_dict1 = {"key1":"value1","key2":[1,2,3]}

#浅拷贝

test_dict2 = test_dict1.copy()

print(test_dict1)

print(test_dict2)

结果:

{'key1': 'value1', 'key2': [1, 2, 3]}
{'key1': 'value1', 'key2': [1, 2, 3]}

现在,修改test_dict1:

test_dict1["key2"] .append("test")

print(test_dict1)

print(test_dict2)

结果:

{'key1': 'value1', 'key2': [1, 2, 3, 'test']}
{'key1': 'value1', 'key2': [1, 2, 3, 'test']}

可见test_dict1的子容器变了,test_dict2的子容器也变了

五、深拷贝

1、语法

import copy

copy.deepcopy(拷贝对象)

2、例子

test_dict1 = {"key1":"val1","key2":[1,2,3]}

test_dict2 = copy.deepcopy(test_dict1)

print(test_dict1)

print(test_dict2)

print(id(test_dict1))

print(id(test_dict2))

结果:

{'key1': 'value1', 'key2': [1, 2, 3]}
{'key1': 'value1', 'key2': [1, 2, 3]}

id:是两个值,说明不是同一内存

2912852694848
2912852767552

修改test_dict1:

test_dict1["key2"] .append("test")

print(test_dict1)

print(test_dict2)

结果:

{'key1': 'value1', 'key2': [1, 2, 3, 'test']}
{'key1': 'value1', 'key2': [1, 2, 3]}

可见test_dict2的子对象还是原来的值,说明深拷贝是拷贝子对象和父对象

六、深浅拷贝内存地址解析

image.png

回帖
请输入回帖内容 ...