The program often needs to replicate an object, as thought should be the case
A = [1, 2, 3]
B = A
# [1, 2, 3]
print B
It's been replicated, but now it's time to change the value of the first element to 5.
B[0] = 5
# [5, 2, 3]
print b
# [5, 2, 3]
print a
I changed the value of the first element of B, but the value of a also changed, because the = in Python is a reference. A and B point to the same list, so changing the list will show the results.
The workaround is a slice operation
A = [1, 2, 3]
B = a[:]
b[0] = 4
# [1, 2, 3]
# [4, 2, 3]
print a
print B
But when it comes to nesting lists, try
a = [[[1,2,3], 4, 5]
B = a[:]
b[1] = 0
# [[1,2,3], 4, 5]
# [[1,2,3], 0, 5]
print a
print B
Well! No problem, try a nested list element
a = [[[1,2,3], 4, 5]
B = a[:]
b[0][0] = 5
# [[5,2,3], 4, 5]
# [[5,2,3], 4, 5]
print a
print B
B = a[:]
The value of a is changed, the slice copy only copies the object and does not copy the child elements
Copy Module
The copy module is used for copy operations on objects. The module is very simple and offers only two main methods: Copy.copy and Copy.deepcopy, respectively, for shallow replication and deep replication. What is a shallow copy, what is a deep copy, the net has a truck a truck of information, here does not give detailed description. The copy operation is valid only for composite objects. Use a simple example to describe the two methods separately.
A shallow copy copies only the object itself and does not copy the object referenced by the object.
#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
Results:
[1, 2, [3, 4]]
[1, 2, [3, 4]]
[1, 2, [4]]
[1, 2, [50, 4]]
The same code, using deep copy, results are different:
Import copy
L1 = [1, 2, [3, 4]]
L2 = copy.deepcopy (L1)
print L1
print L2
l2[2][0] =
Print L1
Print L2
Results:
[1, 2, [3, 4]]
[1, 2, [3, 4]]
[1, 2, [3, 4]]
[1, 2, [50, 4]]
Change the default behavior of copy
When you define a class, you can change the default behavior of copy by defining the __copy__ and __deepcopy__ methods. The following is a simple example:
Class Copyobj (object):
def __repr__ (self): return
"Copyobj"
def __copy__ (self): return
"Hello"
obj = Copyobj ()
obj1 = copy.copy (obj)
print obj
print obj1
Results: