zoukankan      html  css  js  c++  java
  • copy of Python

    copy

    https://docs.python.org/3.5/library/copy.html

      复制运算并不做对象拷贝动作,仅仅是建立一个连接到原始对象。

     如果希望生成一个新的对象,进行修改,不改变原始对象, 则需要拷贝模块。

    拷贝模块提供 深浅拷贝功能。

    Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other. This module provides generic shallow and deep copy operations (explained below).

    Interface summary:

    copy.copy(x)

    Return a shallow copy of x.

    copy.deepcopy(x)

    Return a deep copy of x.

    浅拷贝,仅仅新建一个顶层对象, 顶层对象中如有子对象, 则子对象仅仅做连接操作。

    深拷贝,会将子对象也拷贝出一份新的。

    The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

    • 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.

    DEMO

    https://pymotw.com/3/copy/index.html

    #copy_deep.py
    
    import copy
    import functools
    
    
    @functools.total_ordering
    class MyClass:
    
        def __init__(self, name):
            self.name = name
    
        def __eq__(self, other):
            return self.name == other.name
    
        def __gt__(self, other):
            return self.name > other.name
    
    
    a = MyClass('a')
    my_list = [a]
    dup = copy.deepcopy(my_list)
    
    print('             my_list:', my_list)
    print('                 dup:', dup)
    print('      dup is my_list:', (dup is my_list))
    print('      dup == my_list:', (dup == my_list))
    print('dup[0] is my_list[0]:', (dup[0] is my_list[0]))
    print('dup[0] == my_list[0]:', (dup[0] == my_list[0]))

    The first element of the list is no longer the same object reference, but when the two objects are compared they still evaluate as being equal.

    $ python3 copy_deep.py
    
                 my_list: [<__main__.MyClass object at 0x101e9c160>]
                     dup: [<__main__.MyClass object at 0x1044e1f98>]
          dup is my_list: False
          dup == my_list: True
    dup[0] is my_list[0]: False
    dup[0] == my_list[0]: True
    
  • 相关阅读:
    第五周课堂测试补充
    20162327WJH2016-2017-2《程序设计与数据结构》课程总结
    20162327WJH实验五——数据结构综合应用
    20162327WJH实验四——图的实现与应用
    20162327 《程序设计与数据结构》第十一周学习总结
    20162327WJH第三次实验——查找与排序2
    20162327 《程序设计与数据结构》第九周学习总结
    20162327WJH第二次实验——树
    20162327 《程序设计与数据结构》第七周学习总结
    20162327WJH使用队列:模拟票务站台代码分析
  • 原文地址:https://www.cnblogs.com/lightsong/p/13937432.html
Copyright © 2011-2022 走看看