python中的物件賦值(等號賦值、深複製、淺複製)
阿新 • • 發佈:2019-01-05
程式碼:
輸出: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):
- 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.