Copying objects in python
In python, both parameter passing and function return values are referenced and passed. So how to copy objects? The copy module of the Standard Library provides two methods: copy and deepcopy.
1. copy. copy: only the parent object is copied, and the internal sub-objects of the object are not copied.
2. copy. deepcopy: Deep copy object and its sub-objects
See the following example:
Import copya = [1, 2, 3, 4, ['A', 'B'] # original object e = a [:] # using the multipart operation for copying (shallow copy) B = a # assign a value and pass the reference c = copy of the object. copy (a) # object copy, shortest copy d = copy. deepcopy (a) # object copy, deep copy. append (5) # modify the object aa [4]. append ('C') # modify ['A', 'B'] list sub-object print 'a = ', aprint' B = ', bprint 'C =' in object ', cprint 'd = ', d
Running result:
A = [1, 2, 3, 4, ['A', 'B', 'C'], 5]
B = [1, 2, 3, 4, ['A', 'B', 'C'], 5]
C = [1, 2, 3, 4, ['A', 'B', 'C']
D = [1, 2, 3, 4, ['A', 'B']
E = [1, 2, 3, 4, ['A', 'B', 'C']
Analysis:
B is a reference of a. The two point to the same object, and the printed results must be the same. C Only copies the parent object of a, but does not copy the list of child objects nested in a. Therefore, 1, 2, 3, and 4 in c are copies of their own, however, the nested sub-Object List is still a's original. D. Because it is a deep copy, the parent object of the sub-object is a new copy generated by copying, which is completely unaffected by. As for e, the effect of the multipart operation is equivalent to that of the shortest copy, and the result is the same as that of c.
In addition, the dictionary also has its own copy method, but there is no deepcopy method. Its copy method is the same as the copy method in the copy module above, and it is also the implementation of the shortest copy method.