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

    浅拷贝和深拷贝

    简述

    深浅拷贝的差异仅对复合对象有意义,比如列表,类实例。

    浅拷贝

    拷贝的副本共享内部对象的引用的拷贝为浅拷贝

    举个栗子

    list1 = [1, 2, [3, 4], (5, 6)]
    list2= list(list1)
    print("list1: ", list1, "  list2: ", list2) 
    #list1: [1, 2, [3, 4], (5, 6)] list2: [1, 2, [3, 4], (5, 6)] print("list1 id: ", id(list1), " list2 id: ", id(list2))
    #list1 id: 4940488 list2 id: 38569032 print(" list1 element id:") for ele1 in list1: print(id(ele1))
    #list1 element id: #8791431963472 #8791431963504 #4940424 #34075976 print(" list2 element id:") for ele2 in list2: print(id(ele2)) #list2 element id: #8791431963472 #8791431963504 #4940424 #34075976

    通过类构造函数对list1进行了浅拷贝,通过id(list1)和id(list2)可知list1与list2是两个不同的对象,

    但是list1和list2共享内部对象的引用(由list1与list2中的各个元素的id(ele)可知)

    上述代码的执行如下图:

    浅拷贝方式

    (1)通过类构造函数

    (2)copy模块中的copy方法

    (3)[:](仅对于可变序列)

    深拷贝

    拷贝的副本不共享内部对象的引用的拷贝为深拷贝

    举个栗子

    import copy
    list1 = [1, 2, [3, 4], (5, 6)]
    list2= copy.deepcopy(list1)
    print("list1: ", list1, "  list2: ", list2) 
    #list1: [1, 2, [3, 4], (5, 6)] list2: [1, 2, [3, 4], (5, 6)] print("list1 id: ", id(list1), " list2 id: ", id(list2))
    #list1 id: 35095880 list2 id: 35192776 print(" list1 element id:") for ele1 in list1: print(id(ele1)) #list1 element id: #8791431963472 #8791431963504 #35097928 #34075976 print(" list2 element id:") for ele2 in list2: print(id(ele2)) #list2 element id: #8791431963472 #8791431963504 #35192584 #34075976

    通过copy模块中的deepcopy对list1进行了深拷贝得到list2,由list1与list2的id可知list1与list2是两个不同的对象

    由list1和list2中各个元素的id可知,lis1与list2t中的可变对象不共享对象引用

    上述代码的执行如下图:

    参考资料:<<流畅的python>>

  • 相关阅读:
    java多线程基础(一)
    重构总体思路
    【Gearman学习笔记】分布式处理入门
    virtualbox安装提示出现严重错误解决办法
    驱动程序vmci.sys版本不正确。请尝试重新安装 VMware
    Gearman任务分布系统部署windows平台_使用Cygwin
    Fatal error: Class 'GearmanClient' not found解决方法
    header('Content-type:text/html;charset = utf-8');出现中文乱码
    heredoc和nowdoc的区别
    SELECT INTO 和 INSERT INTO SELECT 两种表复制语句
  • 原文地址:https://www.cnblogs.com/marton/p/10743356.html
Copyright © 2011-2022 走看看