-
直接赋值:其实就是对象的引用(别名)。
-
浅拷贝(copy):拷贝父对象,不会拷贝对象的内部的子对象。
-
深拷贝(deepcopy): copy 模块的 deepcopy 方法,完全拷贝了父对象及其子对象。
实例:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:albert time:2019/1/22
import copy
a = [1,2,3,4,[5,6,7]] # 创建原始对象a
# 赋值
b = a # 将原始对象a赋值给b
# 浅拷贝
c = copy.copy(a) # 浅拷贝a
# 深拷贝
d = copy.deepcopy(b) # 深拷贝b
# 对list父元素修改
a.append(8)
print('a =',a)
print('b =',b)
print('c =',c)
print('d =',d)
print('-'*40)
# 对list子元素修改
b[4].append(10)
print('a =',a)
print('b =',b)
print('c =',c)
print('d =',d)
输出结果:
a = [1, 2, 3, 4, [5, 6, 7], 8]
b = [1, 2, 3, 4, [5, 6, 7], 8]
c = [1, 2, 3, 4, [5, 6, 7]]
d = [1, 2, 3, 4, [5, 6, 7]]
----------------------------------------
a = [1, 2, 3, 4, [5, 6, 7, 10], 8]
b = [1, 2, 3, 4, [5, 6, 7, 10], 8]
c = [1, 2, 3, 4, [5, 6, 7, 10]]
d = [1, 2, 3, 4, [5, 6, 7]]