Python 深浅拷贝
Python 深浅拷贝
http://www.cnblogs.com/aylin/p/5467506.html
a、数字和字符串
对于数字和字符串而言,赋值、浅拷贝和深拷贝无意义,因为其永远指向同一个内存地址。
>>> import copy >>> a = 123 >>> id(a) 9027904 >>> b = a >>> id(b) 9027904 >>> a1 = copy.copy(a) >>> a1 123 >>> id(a1) 9027904 >>> a2 = copy.deepcopy(a) >>> id(a2) 9027904 >>>
b、其他基本数据类型
对于字典、元祖、列表 而言,进行赋值、浅拷贝和深拷贝时,其内存地址的变化是不同的。
赋值,只是创建一个变量,该变量指向原来内存地址
浅拷贝,在内存中只额外创建第一层数据
深拷贝,在内存中将所有的数据重新创建一份(排除最后一层,即:python内部对字符串和数字的优化)
>>> a1 = [1,2,3] >>> a2 = a1 >>> import copy >>> a3 = copy.copy(a1) >>> a4 = copy.deepcopy(a1) >>> id(a1) 140065463143048 >>> id(a2) 140065463143048 >>> id(a3) 140065462442632 >>> id(a4) 140065460223752 >>> a1 [1, 2, 3] >>> a2 [1, 2, 3] >>> a3 [1, 2, 3] >>> a4 [1, 2, 3] >>> >>> a1.append(4) >>> a1 [1, 2, 3, 4] >>> a2 [1, 2, 3, 4] >>> a3 [1, 2, 3] >>> a4 [1, 2, 3] >>> id(a1) 140065463143048 >>> id(a2) 140065463143048 >>> id(a3) 140065462442632 >>> id(a4) 140065460223752 >>> >>> b1 = {'x':'111','y':'222'} >>> type(b1) <class 'dict'> >>> b2 = b1 >>> b3 = copy.copy(b1) >>> b4 = copy.deepcopy(b1) >>> id(b1) 140065460223816 >>> id(b2) 140065460223816 >>> id(b3) 140065457735880 >>> id(b4) 140065463642952 >>> b1 {'x': '111', 'y': '222'} >>> b1['z'] = '333' >>> b1 {'x': '111', 'y': '222', 'z': '333'} >>> b1['x'] = '444' >>> b1 {'x': '444', 'y': '222', 'z': '333'} >>> ... >>> b1 {'x': '444', 'y': '222', 'z': '333'} >>> b2 {'x': '444', 'y': '222', 'z': '333'} >>> b3 {'x': '111', 'y': '222'} >>> b4 {'x': '111', 'y': '222'} >>> >>> id(b1) 140065460223816 >>> id(b2) 140065460223816 >>> id(b3) 140065457735880 >>> id(b4) 140065463642952 >>>