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

来源:互联网 发布:ubuntu搭建hadoop集群 编辑:程序博客网 时间:2024/06/06 01:00

代码:

import copyclass Obj():    def __init__(self,arg):        self.x=argif __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.


0 0
原创粉丝点击