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

Python shallow copy, deep copy and assignment =

編輯:Python
a = {
1:[1,2,3]}

① assignment "=" operation

b = a: Assignment reference ,a and b They all point to the same object .

Be careful : Assignment in use “=” When , The original variable cannot be re assigned , Otherwise, the original variable will point to a new memory address . for example :

example 1:

# use "=" Perform assignment operation 
a = [1,2,3]
b = a
a = [2,3,4]
print(a)
print(b)
""" result : [2, 3, 4] [1, 2, 3] """

example 2:

# The variable a Modify itself 
a = [1,2,3]
b = a
a.append(99)
print(a)
print(b)
"""" result : [1, 2, 3, 99] [1, 2, 3, 99] """

② Shallow copy

b = a.copy(): Shallow copy , a and b Is a separate object , But their sub objects still point to the unified object ( Is quoted ).

copy Children of a complex object are not completely copied , For example, nested sequences in sequences , Nested sequences in the dictionary are all sub objects of complex objects . For child objects ,python It will be stored as a public image , All copies of him are treated as a reference .

③ Deep copy

b = copy.deepcopy(a): Deep copy , a and b It completely copies the parent object and its children , The two are completely independent .


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