python直接赋值、浅拷贝和深拷贝
- 直接赋值:就是对象的引用(别名)
- 浅拷贝(copy):拷贝父对象,不会拷贝对象的内部的子对象
- 深拷贝(deepcopy):copy模块的deepcopy方法,完全拷贝了父对象及其子对象
字典浅拷贝:
>>>a = {1: [1,2,3]} >>> b = a.copy() #浅拷贝 >>> a, b ({1: [1, 2, 3]}, {1: [1, 2, 3]}) >>> a[1].append(4) >>> a, b ({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
字典深拷贝(需要引入copy模块):
>>>import copy #导入copy模块 >>> c = copy.deepcopy(a) #深拷贝 >>> a, c ({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]}) >>> a[1].append(5) >>> a, c ({1: [1, 2, 3, 4, 5]}, {1: [1, 2, 3, 4]})
实例
#!/usr/bin/python # -*-coding:utf-8 -*- import copy a = [1, 2, 3, 4, ['a', 'b']] #原始对象 b = a #赋值,传对象的引用 c = copy.copy(a) #对象拷贝,浅拷贝 d = copy.deepcopy(a) #对象拷贝,深拷贝 a.append(5) #修改对象a a[4].append('c') #修改对象a中的['a', 'b']数组对象 print( 'a = ', a ) print( 'b = ', b ) print( 'c = ', c ) print( 'd = ', d )
以上实例执行输出结果为
('a = ', [1, 2, 3, 4, ['a', 'b', 'c'], 5]) ('b = ', [1, 2, 3, 4, ['a', 'b', 'c'], 5]) ('c = ', [1, 2, 3, 4, ['a', 'b', 'c']]) ('d = ', [1, 2, 3, 4, ['a', 'b']])