Python 直接赋值、浅拷贝和深度拷贝解析
-
直接赋值:其实就是对象的引用(别名)。
-
浅拷贝(copy):拷贝父对象,不会拷贝对象的内部的子对象。
-
深拷贝(deepcopy): copy 模块的 deepcopy 方法,完全拷贝了父对象及其子对象。
1 import copy 2 a = [1, 2, 3, 4, ['a', 'b']] #原始对象 3 4 b = a #赋值,传对象的引用 5 c = copy.copy(a) #对象拷贝,浅拷贝 6 d = copy.deepcopy(a) #对象拷贝,深拷贝 7 8 a.append(5) #修改对象a 9 a[4].append('c') #修改对象a中的['a', 'b']数组对象 10 11 print( 'a = ', a ) 12 print( 'b = ', b ) 13 print( 'c = ', c ) 14 print( 'd = ', d ) 15 16 #结果 17 ('a = ', [1, 2, 3, 4, ['a', 'b', 'c'], 5]) 18 ('b = ', [1, 2, 3, 4, ['a', 'b', 'c'], 5]) 19 ('c = ', [1, 2, 3, 4, ['a', 'b', 'c']]) 20 ('d = ', [1, 2, 3, 4, ['a', 'b']])