python中的对象赋值(等号赋值、深复制、浅复制)

代码:

import copy
class Obj():
    def __init__(self,arg):
        self.x=arg
if __name__ == '__main__':
    obj1=Obj(1)
    obj2=Obj(2)
    obj3=Obj(3)
    obj4=Obj(4)
    lst=[obj1,obj2,obj3,obj4]
    lst1=lst
    lst2=copy.copy(lst)
    lst3=copy.deepcopy(lst)
    print(id(lst),id(lst1),id(lst2),id(lst3))
输出:

(37271888, 37271888, 37688456, 37271816)
从以上输出可以发现,通过等号直接赋值,只能使lst1获得lst的引用,lst1与lst共享同一份数据。而lst2和lst3都获得了自己的一份数据(list),lst2和lst3的区别见下面的代码:

print id(lst),'------>',
    for obj in lst:
        print id(obj),
    print ''
    print id(lst2),'------>',
    for obj in lst2:
        print id(obj),
    print ''
    print id(lst3),'------>',
    for obj in lst3:
        print id(obj),
输出:

13887824 ------> 13888184 13939704 13938768 13941864 
13960256 ------> 13888184 13939704 13938768 13941864 
13887752 ------> 13960184 13960544 13960616 13960688
从以上输出可以发现,lst、lst2、lst3对应的list各不相同,但lst和lst2包含的对象是相同的,也就是说, 浅复制没有进行递归复制,仅复制了最外一层

官网对二者区别的描述:

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

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


  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值