zoukankan      html  css  js  c++  java
  • Python中的浅复制、深复制

    参考

    1. https://docs.python.org/3/library/copy.html?highlight=copy copy#copy.copy
    2. https://en.wikipedia.org/wiki/Object_copying#Shallow_copy

    Fluent Python第四部分第8章

    A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
    A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

    Note:

    1. 直接赋值:其实就是对象的引用(别名)。
    2. 浅复制(shallow copy):copy模块的copy方法,复制父对象,不会复制对象的内部的子对象。
    3. 深复制(deepcopy): copy 模块的 deepcopy 方法,完全复制了父对象及其子对象。
      注意,浅复制和深复制都创建新的对象,所以id()返回的值不同。浅复制的元素使用原始元素的引用(地址),而深复制的元素重拥有新的地址(即深复制copy everything).
      深复制符合我们的认知,复制返回的对象就是一个完全独立的对象。

    例子1. 浅复制

    import copy
    origin_dict = {
        1 : [1,2,3]
    }
    #浅复制可以引入copy模块或者compound objects自带的copy()
    #shcp_didct = origin_dict.copy()
    shcp_dict = copy.copy(origin_dict)
    
    print(id(origin_dict))
    print(id(shcp_dict))
    
    print(origin_dict[1].append(555))
    
    print(origin_dict)
    print(shcp_dict)
    
    

    例子2. 深复制

    #深复制必须引入copy模块
    import copy
    origin_dict = {
        1 : [1,2,3]
    }
    
    shcp_dict = copy.deepcopy(origin_dict)
    
    print(id(origin_dict))
    print(id(shcp_dict))
    
    print(origin_dict[1].append(555))
    
    print(origin_dict)
    print(shcp_dict)
    

  • 相关阅读:
    shell_02
    shell_practise
    Shell_01
    PythonDay_03
    PythonDay_02
    PythonDay_01
    面试题32:从上到下打印二叉树
    面试题 31 : 栈的压入、弹出序列
    面试题20 : 表示数值的字符串
    面试题29:顺时针打印矩阵
  • 原文地址:https://www.cnblogs.com/allen2333/p/8805124.html
Copyright © 2011-2022 走看看