舉例區分Python中的淺複製與深複製

來源:互聯網
上載者:User

   這篇文章主要介紹了舉例區分Python中的淺複製與深複製,是Python入門學習中的重要知識,需要的朋友可以參考下

  copy模組用於對象的拷貝操作。該模組非常簡單,只提供了兩個主要的方法: copy.copy 與 copy.deepcopy ,分別表示淺複製與深複製。什麼是淺複製,什麼是深複製,網上有一卡車一卡車的資料,這裡不作詳細介紹。複製操作只對綜合物件有效。用簡單的例子來分別介紹這兩個方法。

  淺複製只複製對象本身,沒有複製該對象所引用的對象。

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 #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 #---- 結果 ---- [1, 2, [3, 4]] [1, 2, [3, 4]] [1, 2, [50, 4]] [1, 2, [50, 4]]

  同樣的代碼,使用深複製,結果就不一樣:

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 import copy l1 = [1, 2, [3, 4]] l2 = copy.deepcopy(l1) print l1 print l2 l2[2][0] = 50 print l1 print l2 #---- 結果 ---- [1, 2, [3, 4]] [1, 2, [3, 4]] [1, 2, [3, 4]] [1, 2, [50, 4]]

  改變copy的預設行為

  在定義類的時候,通過定義__copy__和__deepcopy__方法,可以改變copy的預設行為。下面是一個簡單的例子:

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 class CopyObj(object): def __repr__(self): return "CopyObj"   def __copy__(self): return "Hello" obj = CopyObj() obj1 = copy.copy(obj) print obj print obj1 #---- 結果 ---- CopyObj Hello

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.