python-深拷贝和浅拷贝
参考书籍:《python核心编程(第二版)》
相关模块:copy模块
1、浅拷贝
浅拷贝:对象赋值是简单的对象引用,当创建一个对象,然后把它赋值给另一个变量的时候,python并没有拷贝这个对象,而是拷贝了这个对象的引用。拷贝的对象本身是新的,但是内容不是,序列类型对象的浅拷贝是默认类型拷贝。如下代码所示:
1 # 浅拷贝 2 s1 = [1, 2, 3] 3 s2 = s1 4 print ('before change s2, s1 = ', s1) 5 print ('before change s2, s2 = ', s2) 6 s2[2] = 20 7 print ('after change s2, s1 = ', s1) 8 print ('after change s2, s2 = ', s2)
输出结果:
1 before change s2, s1 = [1, 2, 3] 2 before change s2, s2 = [1, 2, 3] 3 after change s2, s1 = [1, 2, 20] 4 after change s2, s2 = [1, 2, 20]
2、深拷贝
深拷贝:要得到一个完全拷贝或者深拷贝-创建一个新的容器对象,包含原有对象元素(引用)全新拷贝的引用-需要copy.deepcopy()函数。如下代码所示:
1 s3 = [4, 5, 6] 2 s4 = copy.deepcopy(s3) 3 print ('before change s3, s3 = ', s3) 4 print ('before change s3, s4 = ', s4) 5 s4[2] = 30 6 print ('after change s4, s3 = ', s3) 7 print ('after change s4, s4 = ', s4)
输出结果:
before change s3, s3 = [4, 5, 6] before change s3, s4 = [4, 5, 6] after change s4, s3 = [4, 5, 6] after change s4, s4 = [4, 5, 30]
注意:1、非容器类型(比如数字、字符串和其它“原子”类型的对象,像代码、类型和xrange对象等)没有拷贝一说,浅拷贝是用完全切片操作来完成的;2、如果元组变量只包含原子类型对象,对它的深拷贝将不会进行。