Python深拷貝與淺拷貝

2021-09-25 15:44:10 字數 2793 閱讀 2900

python有個內建的copy的模組專門用於處理深拷貝與淺拷貝,很實用,用起來也很方便,能為我們省去不少麻煩,不用自己再寫深拷貝或者淺拷貝物件的方法了。

賦值,淺拷貝,深拷貝只針對可變變數,如list,dict,tuple

python中賦值都是進行記憶體位址的傳遞

淺拷貝(copy,copy())只會賦值物件,重新申請記憶體位址,但對於物件中的元素依然是原始的記憶體位址引用

如果要完全拷貝乙個物件,請使用copy.deepcopy()

#coding=utf-8

from copy import copy, deepcopy

if __name__ ==

"__main__"

:print

('deepcopy'

) a=[1

,[11,

2,3]

]; b=deepcopy(a)

print

('id(a) =',id

(a))

for i in

range(0

,len

(a))

:print(%

(i,id

(a[i]))

)print

('id(b) =',id

(b))

for i in

range(0

,len

(b))

:print(%

(i,id

(b[i]))

)print

('\ncopy'

) a=[1

,[11,

2,3]

]; b=copy(a)

print

('id(a) =',id

(a))

for i in

range(0

,len

(a))

:print(%

(i,id

(a[i]))

)print

('id(b) =',id

(b))

for i in

range(0

,len

(b))

:print(%

(i,id

(b[i]))

)

#coding=utf-8

from copy import copy, deepcopy

class

node

(object):

@classmethod

def__new__

(cls,

*args,

**kwargs)

: self =

super()

.__new__(cls)

print

('__new__ of '

, self)

return self

def__init__

(self)

:print

('__init__ of '

, self)

self.father =

none

;self.isme =

false

; self.children =

defaddchild

(self, child)

: child.father = self

return self

class

subtreenode

(node)

:def

__init__

(self,):

super()

.__init__(

) self.weight =

1if __name__ ==

"__main__"

: n = subtreenode(

).addchild(subtreenode())

n = subtreenode(

).addchild(n)

print

('\n------深拷貝只呼叫__new__方法,而不再呼叫__init__方法--------'

) n2 = deepcopy(n)

print

('\n------物件的位址資訊--------'

)print(id

(n),

id(n.children[0]

),id(n.children[0]

.children[0]

))print(id

(n2),id

(n2.children[0]

),id(n2.children[0]

.children[0]

))print

('\n------物件的屬性資訊--------'

) n.weight =

8print

(n.weight, n2.weight)

n.children[0]

.weight =

9print

(n.children[0]

.weight, n2.children[0]

.weight)

n.children[0]

.children[0]

.weight =

10print

(n.children[0]

.children[0]

.weight, n2.children[0]

.children[0]

.weight)

Python 淺拷貝與深拷貝

淺拷貝 構造方法或切片 做的是淺拷貝 即拷貝了最外層容器,副本中的元素是原容器中元素的引用 在 python 中,通過乙個物件向另外乙個物件賦值,實際僅僅是賦值了物件的引用,而非建立乙個物件並賦值。那如何真正拷貝物件呢?我們看一下兩種不同的拷貝方式。先從乙個示例看起 anndy anndy age ...

Python 淺拷貝與深拷貝

以下例項是使用 copy 模組的 copy.copy 淺拷貝 和 copy.deepcopy usr bin python coding utf 8 import copy a 1,2,3,4,a b 原始物件 b a 賦值,傳物件的引用 c copy.copy a 物件拷貝,淺拷貝 d copy....

python 深拷貝與淺拷貝

當乙個變數 的時候,約定為 指向位址的過程 如果copy.copy 拷貝的是元組,那麼它不會進行淺拷貝,僅僅是指向 因為元組是不可變資料型別,那麼意味著資料一定不能修改,因此用copy.copy的 時候它會自動判斷,是指向。如果,用copy.copy copy.deepcopy 對乙個全部是不可變型...