栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python 浅拷贝与深拷贝 shallow and deep copy

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python 浅拷贝与深拷贝 shallow and deep copy

Python 中的一切都是对象,以下代码:

赋值

赋值只是简单地使新变量指向已经存在的对象:

numbers = [1, 2, 3, 4, 5]
new_numbers = numbers

numbers 与 new_numbers 指向相同的对象,修改 numbers 就是在修改 new_numbers 。
id(numbers) == id(b) 或者 numbers is new_numbers 都为 True.

浅拷贝与深拷贝

浅拷贝和深拷贝之间的区别仅与复合对象(包含其他对象的对象,如列表或类实例)相关。

浅拷贝复制得到新的复合对象,但引用原始对象的元素。
深拷贝复制得到新的复合对象,并复制该组成原始对象的元素。

要复制对象,需要使用内建模块 copy

调用 copy.copy() 实现浅拷贝:
import copy

old_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
shallow_list = copy.copy(old_list)

print(old_list)
print(shallow_list)

print(old_list is shallow_list)
print(old_list[0] is shallow_list[0])

old_list[0][0] = "x"
print(old_list)
print(shallow_list)

输出:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
False
True
[['x', 2, 3], [4, 5, 6], [7, 8, 9]]
[['x', 2, 3], [4, 5, 6], [7, 8, 9]]
调用 copy.deepcopy() 实现浅拷贝:
old_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
deep_list = copy.deepcopy(old_list)

print(old_list)
print(deep_list)

print(old_list is deep_list)
print(old_list[0] is deep_list[0])

old_list[0][0] = "x"
print(old_list)
print(deep_list)

输出:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
False
False
[['x', 2, 3], [4, 5, 6], [7, 8, 9]]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1009926.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号