前言
最近做python工程,由于一直用c++,没有系统学习过python,犯了一个严重的错误,那就是Python中的对象之间赋值
时是按引用传递!!!!也就是更改了赋值的新对象,两个值都会变化。如果需要拷贝对象,需要使用标准库中的copy模块。
深拷贝与浅拷贝
- 1.copy.copy 浅拷贝 只拷贝父对象,不会拷贝对象的内部的子对象.
- 2.copy.deepcopy 深拷贝 拷贝对象及其子对象
例子
a = [1,2,3,4,['a','b']]
b = a
b[2]=10
print 'b = ',b
print 'a = ',a
print '-----------------------------'
c = copy.copy(a)
c[2]=20
print 'c = ',c
print 'a = ',a
print '-----------------------------'
d = copy.deepcopy(a)
d[2]=30
print 'd = ',d
print 'a = ',a
print '-----------------------------'
a.append(5)
a[4].append('c')
print 'a = ', a
print 'b = ', b
print 'c = ', c
print 'd = ', d
输出结果
b = [1, 2, 10, 4, [‘a’, ‘b’]]
a = [1, 2, 10, 4, [‘a’, ‘b’]]
a = [1, 2, 10, 4, [‘a’, ‘b’]]
a = [1, 2, 10, 4, [‘a’, ‘b’]]
b = [1, 2, 10, 4, [‘a’, ‘b’, ‘c’], 5]
d = [1, 2, 30, 4, [‘a’, ‘b’]]