zoukankan      html  css  js  c++  java
  • 深浅拷贝

    1. = 没有创建新对象, 只是把内存地址进行了复制
    2. 浅拷贝 lst.copy() 只拷贝第一层.
    3. 深拷贝
    import copy
    copy.deepcopy() 会把对象内部的所有内容进行拷贝

    # # 从上到下只有一个列表被创建
    # 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)
    
    
    # 为什么要有深浅拷贝?
    # 提高创建对象的速度
    # 计算机中最慢的. 就是创建对象. 需要分配内存.
    # 最快的方式就是二进制流的形式进行复制. 速度最快.
    
    # 做作业? 抄作业?
    

      

  • 相关阅读:
    fastjson 简单使用 及其JSONObject使用
    HttpClient 的使用
    python操作excel xlwt (转)
    matplotlib 设置标题 xy标题等
    matplotlib 饼状图
    Mac下面 matplotlib 中文无法显示解决
    matplotlib 折线图
    matplotlib条形图
    matplotlib直方图
    python matplotlib配置
  • 原文地址:https://www.cnblogs.com/YangWenYu-6/p/10073485.html
Copyright © 2011-2022 走看看