程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Copy, shallow copy and deep copy in Python

編輯:Python

1. The three elements of object

id、type as well as value,id Uniquely identifies an object , Equivalent to address ,id equally , It means the same thing .type and value Literally .

2.== and is

== The comparison is value,is The comparison is id, intend   “ Is it the same object ”, Conditions are better than == Be strict .

3. The variable object / Immutable object

Python Everything is an object , Immutable objects have : Numbers 、 character string 、 Tuples etc. , Why are immutable objects ? Can't I reassign an integer variable ? I believe there must also be such doubts , Here's an example :

I can see , by a Reassign , Actually, it's order a Points to another object , character string , Tuple is also a truth , Modify the variables that point to such objects , Just make it point to another object .

And for mutable objects , Such as list, As shown in the figure below , After modification id unchanged , Or this thing

4. assignment 、 Shallow copy and deep copy

For immutable objects , These three functions are the same , Make the new variable point to the immutable object , therefore id It's all the same :

For mutable objects , Assignment is the simplest and easiest , Such as b=a, It means to make directly a Point to b Represented by , both id equally , Point to the same object , A modification , The other one changes with it :

Shallow copy copy.copy Is to create another object , Such as a=[1,2,[1,2]],b=copy.copy(a),a And b Of id Different , But the content is the same , such as a[2] and b[2] Still point to the same object , Modify one of , The other one will also change :

A deep copy is a complete copy , Or the example above , After deep copy , Not only a and b Of id Different . Connect the objects inside id Also different ( Except for immutable objects ), One change does not affect the other , Here's the picture :

The above is my humble opinion , If there is any wrong , I would also like to point out that .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved