python中的赋值、copy、deepcopy
import copy ''' 直接赋值:其实就是对象的引用(别名)。 copy 模块的 copy 方法,拷贝父对象,不会拷贝对象的内部的子对象。 copy 模块的 deepcopy 方法,完全拷贝了父对象及其子对象。 ''' origin = [1, 2, [3, 4]] cop1 = copy.copy(origin) cop2 = copy.deepcopy(origin) cop3=origin print(origin) print(cop1) print(cop2) print(cop3) origin[2][0] = "hey!" #改变 print("##################") print(origin) print(cop1) print(cop2) # 深度拷贝不变 print(cop3) [1, 2, [3, 4]] [1, 2, [3, 4]] [1, 2, [3, 4]] [1, 2, [3, 4]] ################## [1, 2, ['hey!', 4]] [1, 2, ['hey!', 4]] [1, 2, [3, 4]] [1, 2, ['hey!', 4]]
这个原理适用于list、dict数据类型。下面再放一个dict类型的例子。
import copy print("使用copy") dict1={"key1":"val1","k1":{"name":"lilei"}} dict2=copy.copy(dict1) print("dict1= %r" % dict1) print("dict2= %r" % dict2) dict1["key1"] = "val1_new" print("dict1= %r" % dict1) print("dict2= %r" % dict2) dict1["k1"]["name"] = "lilei_new" print("dict1= %r" % dict1) print("dict2= %r" % dict2) print("\n") print("---------------") print("使用deepcopy") dict1={"key1":"val1","k1":{"name":"lilei"}} dict2=copy.deepcopy(dict1) print("dict1= %r" % dict1) print("dict2= %r" % dict2) dict1["key1"] = "val1_new" print("dict1= %r" % dict1) print("dict2= %r" % dict2) dict1["k1"]["name"] = "lilei_new" print("dict1= %r" % dict1) print("dict2= %r" % dict2) ''' 使用copy dict1= {'key1': 'val1', 'k1': {'name': 'lilei'}} dict2= {'key1': 'val1', 'k1': {'name': 'lilei'}} dict1= {'key1': 'val1_new', 'k1': {'name': 'lilei'}} dict2= {'key1': 'val1', 'k1': {'name': 'lilei'}} dict1= {'key1': 'val1_new', 'k1': {'name': 'lilei_new'}} dict2= {'key1': 'val1', 'k1': {'name': 'lilei_new'}} --------------- 使用deepcopy dict1= {'key1': 'val1', 'k1': {'name': 'lilei'}} dict2= {'key1': 'val1', 'k1': {'name': 'lilei'}} dict1= {'key1': 'val1_new', 'k1': {'name': 'lilei'}} dict2= {'key1': 'val1', 'k1': {'name': 'lilei'}} dict1= {'key1': 'val1_new', 'k1': {'name': 'lilei_new'}} dict2= {'key1': 'val1', 'k1': {'name': 'lilei'}} '''