Home  >  Article  >  Backend Development  >  Python浅拷贝与深拷贝用法实例

Python浅拷贝与深拷贝用法实例

WBOY
WBOYOriginal
2016-06-10 15:12:571294browse

本文实例讲述了Python浅拷贝与深拷贝用法。分享给大家供大家参考。具体分析如下:

>>> person=['name',['savings',100]]
>>> hubby=person[:]
>>> wifey=list(person)
>>> [id(x) for x in person,hubby,wifey]
[3074051788L, 3074061740L, 3074061996L]
>>> [id(y) for x in person,hubby,wifey for y in x]
[3074319552L,3073979916L,3074319552L,3073979916L,3074319552L,3073979916L]
>>> hubby[0]='joe'
>>> wifey[0]='jane'
(['joe',['savings',100]],['jane',['savings',100]],['name',['savings',100]])
>>> hubby[1][1]=70
>>> hubby,wifey,person
(['joe',['savings',70]],['jane',['savings',70]],['name',['savings',70]])

浅拷贝,创造了新的对象,但是它的对象引用确和被拷贝对象一致。

如果被拷贝对象的构成元素是不可变类型,则拷贝对象对这个元素的改变,实际上是创造一个新的对象。

如果被拷贝对象的构成元素是可变类型,则拷贝对象对这个元素的改变,实际上是在原对象的内存空间上修改这个内存空间里面的内容。

这样,才有hubby[1][1]=70会导致wifey,person相应值的改变。

希望本文所述对大家的Python程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn