一.深浅拷贝
1. = 没有创建新对象, 只是把内存地址进行了复制
1 从上到下只有一个列表被创建
2 lst1 = ["胡辣汤", "灌汤包", "油泼面", "麻辣香锅"]
3 lst2 = lst1 # 并没有产生新对象. 只是一个指向(内存地址)的赋值
4 print(id(lst1))
5 print(id(lst2))
6
7 lst1.append("葫芦娃")
8 print(lst1)
9 print(lst2)
2. 浅拷贝 lst.copy() 只拷贝第一层.
1 lst1 = ["胡辣汤", "灌汤包", "油泼面", "麻辣香锅"]
2 lst2 = lst1.copy() # 拷贝, 抄作业, 可以帮我们创建新的对象, 和原来长的一模一样, 浅拷贝
3
4 print(id(lst1))
5 print(id(lst2))
6
7 lst1.append("葫芦娃")
8 print(lst1)
9 print(lst2)
1 lst1 = ["胡辣汤", "灌汤包", "油泼面", "麻辣香锅",["长白山", "白洋淀", "黄鹤楼"]]
2 lst2 = lst1.copy() # 浅拷贝. 只拷贝第一次内容
3
4 print(id(lst1))
5 print(id(lst2))
6
7 print(lst1)
8 print(lst2)
9
10 lst1[4].append("葫芦娃")
11 print(lst1)
12 print(lst2)
3. 深拷贝
import copy
copy.deepcopy() 会把对象内部的所有内容进行拷贝
1 import copy
2 lst1 = ["胡辣汤", "灌汤包", "油泼面", "麻辣香锅",["长白山", "白洋淀", "黄鹤楼"]]
3 lst2 = copy.deepcopy(lst1) # 深拷贝:对象内部的所有内容都要复制一份. 深度克隆(clone). 原型模式
4
5 print(id(lst1))
6 print(id(lst2))
7
8 print(lst1)
9 print(lst2)
10
11 lst1[4].append("葫芦娃")
12 print(lst1)
13 print(lst2)
科普为什么要有深浅拷贝?提高创建对象的速度计算机中最慢的. 就是创建对象. 需要分配内存.最快的方式就是二进制流的形式进行复制. 速度最快
来源:https://www.cnblogs.com/beargod/p/10066396.html