美文网首页
Python学习笔记之拷贝

Python学习笔记之拷贝

作者: 狗子渣渣 | 来源:发表于2017-12-21 14:30 被阅读6次

Python的对象分为两种:可变(List,Dict)和不可变对象(String, Truple)
对于对Python对象和变量的理解:图解Python变量与赋值
修改可变对象不需要开辟新的内存地址,修改不可变对象需要开辟新的内存地址
拷贝问题对于可变对象和不可变对象来说是不一样的。
可变对象:浅拷贝和深拷贝完全复制了对象的内存地址
不可变对象:浅拷贝完全复制了对象的内存地址,而深拷贝则是复制了对象本身,并且重新开辟内存空间

代码示例:

>>> import copy
>>> a = ["hello", [1,2,3,4]]
>>> b = a
>>> c = copy.copy(a)
>>> d = copy.deepcopy(a)
>>> [id(x) for x in a]
[54182720, 54020488]
>>> [id(x) for x in b]
[54182720, 54020488]
>>> [id(x) for x in c]
[54182720, 54020488]
>>> [id(x) for x in d]
[54182720, 54018440]
>>> a[0] = "world"
>>> a[1].append(5)
>>> [id(x) for x in a]
[54182832, 54020488]
>>> [id(x) for x in b]
[54182832, 54020488]
>>> [id(x) for x in c]
[54182720, 54020488]
>>> [id(x) for x in d]
[54182720, 54018440]
>>> print(a)
['world', [1, 2, 3, 4, 5]]
>>> print(b)
['world', [1, 2, 3, 4, 5]]
>>> print(c)
['hello', [1, 2, 3, 4, 5]]
>>> print(d)
['hello', [1, 2, 3, 4]]

相关文章

网友评论

      本文标题:Python学习笔记之拷贝

      本文链接:https://www.haomeiwen.com/subject/fokawxtx.html