标签:
Python中,对象的赋值,拷贝(深/浅拷贝)之间是有差异的,如果使用的时候不注意,就可能产生意外的结果。
下面本文就通过简单的例子介绍一下这些概念之间的差别。
直接看一段代码:
will = ["Will", 28, ["Python", "C#", "JavaScript"]] wilber = 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]
代码的输出为:
下面来分析一下这段代码:
下面就来看看浅拷贝的结果:
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]
代码结果为:
分析一下这段代码:
总结一下,当我们使用下面的操作的时候,会产生浅拷贝的效果:
最后来看看深拷贝:
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]
代码的结果为:
分析一下这段代码:
其实,对于拷贝有一些特殊情况:
本文介绍了对象的赋值和拷贝,以及它们之间的差异:
标签:
原文地址:http://www.cnblogs.com/wilber2013/p/4645353.html