Python对象赋值浅拷贝深拷贝

Posted bqwzx

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python对象赋值浅拷贝深拷贝相关的知识,希望对你有一定的参考价值。


Python中,基本数据类型,理解为常见数据类型:布尔型、整型、浮点型、字符串、列表、元组、字典、集合,随语言不同而不同,但是根据在内存中存储方式的不同,区分开原子类型和容器类型。

对象赋值

对象的赋值都是进行(对象引用传递)/(内存地址传递)/(内存引用),所以当一个对象改变,另一个同步改变。

结合代码思考
···
will = ["Will", 28, ["Python", "C#", "javascript"]] # 元素的数据类型有原子类型和容器类型
wilber = will
print id(will) # will的id
print will
print [id(ele) for ele in will] # will中每个元素的id
print id(wilber) # wilber的id == will的id
print wilber

will[0] = "Wilber" # 改动will中的元素0
will[2].append("CSS") # 改动will中的元素2
print id(will) # will的id没变
print will
print [id(ele) for ele in will]
print id(wilber) # wilber
print wilber
print [id(ele) for ele in wilber]
···

浅拷贝

浅拷贝对象是容器类型,原子类型只有对象赋值。浅拷贝会新起一个对象,将原容器包含的内存地址引用过去。当原容器包含的元素有可变的(即容器对象),容器元素的改变也会引起新拷贝对象内元素的改变。

结合代码思考

import copy

will = ["Will", 28, ["Python", "C#", "JavaScript"]]
wilber = copy.copy(will)

print id(will)
print will
print [id(ele) for ele in will]
print id(wilber)
print wilber
print [id(ele) for ele in wilber]

will[0] = "Wilber"
will[2].append("CSS")
print id(will)
print will
print [id(ele) for ele in will]
print id(wilber)
print wilber
print [id(ele) for ele in wilber]

深拷贝

深拷贝对象也是容器类型,原子类型只有对象赋值。深拷贝和浅拷贝一样,也会根据原对象深拷贝新起一个对象,但是会将元素里面的容器类型的新拷贝一份(默认深入新拷贝层数好像是1),因此原对象的容器元素改变了,新对象的容器元素不会改变。

结合代码思考

import copy

will = ["Will", 28, ["Python", "C#", "JavaScript"]]
wilber = copy.deepcopy(will)

print id(will)
print will
print [id(ele) for ele in will]
print id(wilber)
print wilber
print [id(ele) for ele in wilber]

will[0] = "Wilber"
will[2].append("CSS")
print id(will)
print will
print [id(ele) for ele in will]
print id(wilber)
print wilber
print [id(ele) for ele in wilber]

总结

数据结构+算法,需要反复学习+理解+记忆。


https://www.cnblogs.com/wilber2013/p/4645353.html#_nav_1

以上是关于Python对象赋值浅拷贝深拷贝的主要内容,如果未能解决你的问题,请参考以下文章

python-深拷贝和浅拷贝

python中赋值-浅拷贝-深拷贝之间的关系

Python 赋值浅拷贝和深拷贝

python直接赋值浅拷贝与深拷贝的区别解析

python深拷贝浅拷贝

总结:Python的赋值深拷贝浅拷贝有什么区别