1、无论是浅拷贝还是深拷贝,拷贝对象后是否会开辟新内存,取决于被拷贝对象的数据类型是否可变,一般来讲,可变的数据类型会开辟新内存,不可变数据类型反之不会开辟新内存,进行内存地址的引用(-5-256以外的大整数池会开辟内存,但我本地进行测试比较内存还是一样的,有问题)

2、要在单层、嵌套型对象中逐一比较拷贝

3、浅拷贝和深拷贝的区别主要体现在对嵌套型结构的拷贝上

 1 import copy
 2 
 3 print("================赋值==================")
 4 prototype_lst = [1, 2, 5, [78, 90]]
 5 a = prototype_lst
 6 prototype_lst.append(9)
 7 print(prototype_lst, a)
 8 
 9 print("================浅拷贝==================")
10 prototype_lst.pop(-1)
11 shallow_b = prototype_lst.copy()
12 # 原始列表子对象发生变化,拷贝对象后内部子对象也跟着改变
13 prototype_lst[-1].append(100)
14 print("原始列表:", prototype_lst, "拷贝后列表:", shallow_b)
15 
16 print("================深拷贝==================")
17 deep_b = copy.deepcopy(prototype_lst)
18 # 原始列表子对象发生变化,拷贝对象后内部子对象不变
19 prototype_lst[-1].append(0)
20 print("原始列表:", prototype_lst, "拷贝后列表:", deep_b)
21 
22 # 不可变数据类型的浅拷贝和深拷贝
23 prototype_tuple = (1, 2)
24 shallow_c = copy.copy(prototype_tuple)
25 deep_c = copy.deepcopy(prototype_tuple)
26 print(id(shallow_c) == id(deep_c))

output:

  ================赋值==================
  [1, 2, 5, [78, 90], 9] [1, 2, 5, [78, 90], 9]
  ================浅拷贝==================
  原始列表: [1, 2, 5, [78, 90, 100]] 拷贝后列表: [1, 2, 5, [78, 90, 100]]
  ================深拷贝==================
  原始列表: [1, 2, 5, [78, 90, 100, 0]] 拷贝后列表: [1, 2, 5, [78, 90, 100]]
  True

发表回复