python direct assignment, deep shallow copy copy distinction resolved


Direct assignment: in fact, object reference (alias).

Shallow copy (copy): copy child objects inside the parent object, the object will not be copied.

Deep copy (deepcopy): deepcopy method copy module, complete copy of the parent object and child objects.

Analysis examples
A = {. 1: [l, 2,3]}
1. A b =: assignment references, a and b are the same object, as shown below:
 
2. b = a.copy (): shallow copy, A and b is an independent object, but their child object or to the consolidated object (reference), as shown below:
 
3. copy.deepcopy b = (a): you need to import the copy module, a deep copy, a and b completely copied parent object and its children, the two are completely separate, as shown below:


For example:

>>>a = {1: [1,2,3]}
>>> b = a.copy()
>>> a, b
({1: [1, 2, 3]}, {1: [1, 2, 3]})
>>> a[1].append(4)
>>> a, b
({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
>>>import copy
>>> c = copy.deepcopy(a)
>>> a, c
({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
>>> a[1].append(5)
>>> a, c
({1: [1, 2, 3, 4, 5]}, {1: [1, 2, 3, 4]})
import copy
a = [1, 2, 3, 4, ['a', 'b']] #原始对象

b = a # reference assignment, transfer object
c = copy.copy (a) # copy of the object, shallow copy
d = copy.deepcopy (a) # copy of the object, a deep copy

a.append (5) # modify object a
a [. 4] .append ( 'C') # modify objects in a [ 'a', 'b' ] array object

print( 'a = ', a )
print( 'b = ', b )
print( 'c = ', c )
print( 'd = ', d )

Output ### ###
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 ']]
summary:
1, the assignment: reference simple copy of the object, the two objects of the same id.
2, shallow copy: create a new composite object, the new object with the original object is a shared object in memory.
3, deep copy: create a new composite object, and recursively copy all child objects, the new composite object with the original object has no relevance. Although it will actually shared sub-objects immutable, but does not affect their mutual independence.

Shallow vs. deep copy is merely a combination of different objects, composite object is called the object contains other objects, such as a list of instances of classes. For numeric, string, and other types of "atom", not a copy, said original reference object is produced.

Guess you like

Origin www.cnblogs.com/jeasonit/p/12052828.html