copy and deepcopy in Python

Base

  1. ==The condition for to be established in python is value is the same
  2. isThe condition for to be established in python is id is the same
  3. =It is an assignment operator that can create a binding relationship between a target and an object.
  4. A composite object is an object that contains other objects such as lists or instances of a class
  5. For immutable objects such as strings, tuples, integers, etc., using copy or deepcopy is redundant because they cannot be modified, so There is no "deep copy" or "shallow copy" problem.

use

import copy
str1 = "str1"

str1_copy = copy.copy(str1)
str1_deep_copy = copy.deepcopy(str1)

difference

  1. When using non-composite objects, the two functions have the same effect. They both return a copy of the original object (with different IDs, modifications will not change the original object).
  2. In the use of composite objects,copy will insert the objects in the original object引用 into it
  3. When using composite objects,deepcopy will recursively insert the objects in the original object生成副本 into it

example

import copy

list1 = [1, 2, 3, 4, ['a', 'b']]

list2 = copy.copy(list1)
list3 = copy.deepcopy(list1)

print(list2, list3)
print(id(list1), id(list2), id(list3))
print((list1==list2), (list1==list3))
print((list1 is list2), (list1 is list3))
list2.append(5)
list3.append(6)
list1.append(7)
list1[0] = 0
# list1[4] = 999
list2[4].append(777)
print(list1, list2, list3)
print(id(list1), id(list2), id(list3))

# Here is output
[1, 2, 3, 4, ['a', 'b']] [1, 2, 3, 4, ['a', 'b']]
4365056832 4365056896 4365057024
True True
False False
[0, 2, 3, 4, ['a', 'b', 777], 7] [1, 2, 3, 4, ['a', 'b', 777], 5] [1, 2, 3, 4, ['a', 'b'], 6]
4365056832 4365056896 4365057024

おすすめ

転載: blog.csdn.net/majiayu000/article/details/132859066