深浅拷贝

# # 从上到下只有一个列表被创建
# lst1 = ["胡辣汤", "灌汤包", "油泼面", "麻辣香锅"]
# lst2 = lst1  # 并没有产生新对象. 只是一个指向(内存地址)的赋值
# print(id(lst1))
# print(id(lst2))
#
# lst1.append("葫芦娃")
# print(lst1)
# print(lst2)



# lst1 = ["胡辣汤", "灌汤包", "油泼面", "麻辣香锅"]
# lst2 = lst1.copy()  # 拷贝, 抄作业, 可以帮我们创建新的对象,和原来长的一模一样, 浅拷贝
#
# print(id(lst1))
# print(id(lst2))
#
# lst1.append("葫芦娃")
# print(lst1)
# print(lst2)



# lst1 = ["胡辣汤", "灌汤包", "油泼面", "麻辣香锅", ["长白山", "白洋淀", "黄鹤楼"]]
# lst2 = lst1.copy() # 浅拷贝. 只拷贝第一层内容
#
# print(id(lst1))
# print(id(lst2))
#
# print(lst1)
# print(lst2)
#
# lst1[4].append("葫芦娃")
# print(lst1)
# print(lst2)

# 引入一个模块
import copy

lst1 = ["胡辣汤", "灌汤包", "油泼面", "麻辣香锅", ["长白山", "白洋淀", "黄鹤楼"]]
lst2 = copy.deepcopy(lst1) # 深拷贝: 对象内部的所有内容都要复制一份. 深度克隆(clone). 原型模式

print(id(lst1))
print(id(lst2))

print(lst1)
print(lst2)

lst1[4].append("葫芦娃")
print(lst1)
print(lst2)


# 为什么要有深浅拷贝?
# 提高创建对象的速度
# 计算机中最慢的. 就是创建对象. 需要分配内存.
# 最快的方式就是二进制流的形式进行复制. 速度最快.

# 做作业? 抄作业?

  

posted @ 2018-12-04 17:48  =-=-  阅读(96)  评论(0编辑  收藏  举报