舉例區(qū)分Python中的淺復(fù)制與深復(fù)制
copy模塊用于對象的拷貝操作。該模塊非常簡單,只提供了兩個主要的方法: copy.copy 與 copy.deepcopy ,分別表示淺復(fù)制與深復(fù)制。什么是淺復(fù)制,什么是深復(fù)制,網(wǎng)上有一卡車一卡車的資料,這里不作詳細介紹。復(fù)制操作只對復(fù)合對象有效。用簡單的例子來分別介紹這兩個方法。
淺復(fù)制只復(fù)制對象本身,沒有復(fù)制該對象所引用的對象。
#coding=gbk import copy l1 = [1, 2, [3, 4]] l2 = copy.copy(l1) print l1 print l2 l2[2][0] = 50 print l1 print l2 #---- 結(jié)果 ---- [1, 2, [3, 4]] [1, 2, [3, 4]] [1, 2, [50, 4]] [1, 2, [50, 4]]
同樣的代碼,使用深復(fù)制,結(jié)果就不一樣:
import copy l1 = [1, 2, [3, 4]] l2 = copy.deepcopy(l1) print l1 print l2 l2[2][0] = 50 print l1 print l2 #---- 結(jié)果 ---- [1, 2, [3, 4]] [1, 2, [3, 4]] [1, 2, [3, 4]] [1, 2, [50, 4]]
改變copy的默認行為
在定義類的時候,通過定義__copy__和__deepcopy__方法,可以改變copy的默認行為。下面是一個簡單的例子:
class CopyObj(object):
def __repr__(self):
return "CopyObj"
def __copy__(self):
return "Hello"
obj = CopyObj()
obj1 = copy.copy(obj)
print obj
print obj1
#---- 結(jié)果 ----
CopyObj
Hello

