最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

舉例區(qū)分Python中的淺復(fù)制與深復(fù)制

 更新時(shí)間:2015年07月02日 12:15:02   作者:DarkBull  
這篇文章主要介紹了舉例區(qū)分Python中的淺復(fù)制與深復(fù)制,是Python入門學(xué)習(xí)中的重要知識(shí),需要的朋友可以參考下

copy模塊用于對(duì)象的拷貝操作。該模塊非常簡(jiǎn)單,只提供了兩個(gè)主要的方法: copy.copy 與 copy.deepcopy ,分別表示淺復(fù)制與深復(fù)制。什么是淺復(fù)制,什么是深復(fù)制,網(wǎng)上有一卡車一卡車的資料,這里不作詳細(xì)介紹。復(fù)制操作只對(duì)復(fù)合對(duì)象有效。用簡(jiǎn)單的例子來分別介紹這兩個(gè)方法。

淺復(fù)制只復(fù)制對(duì)象本身,沒有復(fù)制該對(duì)象所引用的對(duì)象。
 

#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的默認(rèn)行為

在定義類的時(shí)候,通過定義__copy__和__deepcopy__方法,可以改變copy的默認(rèn)行為。下面是一個(gè)簡(jiǎn)單的例子:
 

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

相關(guān)文章

最新評(píng)論

九龙坡区| 白水县| 盐城市| 锡林郭勒盟| 镇坪县| 永兴县| 光泽县| 修水县| 黔东| 达日县| 五峰| 平罗县| 绥化市| 金川县| 阿巴嘎旗| 乡宁县| 武平县| 信阳市| 大新县| 玉树县| 尼勒克县| 和顺县| 瑞金市| 平山县| 闻喜县| 焉耆| 巴青县| 叶城县| 宣恩县| 泰安市| 日照市| 吉隆县| 建德市| 天镇县| 景东| 乃东县| 上林县| 丰镇市| 仪征市| 屯昌县| 临夏市|