copy深浅拷贝

import copy

# 浅拷贝
# copy.copy()

# 深拷贝
# copy.deepcopy()

# 赋值
s1 = '1234'
s2 = 456
t1 = s1
t2 = s2
c1 = copy.copy(s1)
c2 = copy.deepcopy(s1)
print(id(s1), id(t1), id(c1), id(c2), id(s2), id(t2))

# 浅拷贝
l1 = ['1234', 'fhgo', (1, 3, 4, 5), [1, 2, 3, 4], {'a': 'a', 'b': 'b'}]
l2 = copy.copy(l1)
print(id(l1), id(l2))
'''
浅拷贝只在新内存空间拷贝了l1最外层, 所以l2的元素[3]地址还是l1的元素地址
, 那么在l1的原有元素[3]地址改变内容, l2也会改变, l1的新增元素, 则不会影响l2
'''
l1[3].append(5)
l1[0] = 'aaa'
print(l1, l2, id(l1[3]), id(l2[3]), 'l1原有元素3新增5,影响了l2的元素3')
l1.append(6)
print(l1, l2, 'l1新增6没影响l2')


# 深拷贝
l1 = ['1234', 'fhgo', (1, 3, 4, 5), [1, 2, 3, 4], {'a': 'a', 'b': 'b'}]
l2 = copy.deepcopy(l1)
'''
深拷贝在新空间地址,将l1每层元素都拷贝(字符串和数字,不会拷贝),所以改变l1不会改变l2
'''
l1[3].append(5)
l1[0]='aaa'
print(l1, l2, id(l1[0]), id(l2[0]), 'l1原有元素3新增5,没影响l2的元素3')
l1.append(6)
print(l1, l2, 'l1新增6没影响l2')


exit()

  

posted @ 2017-03-12 18:05  破斧呈粥  阅读(152)  评论(0编辑  收藏  举报