Case Analysis of Python Direct assignment, shallow copy and Deep copy
This article mainly explains the "Python direct assignment, shallow copy and deep copy of the case analysis", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "Python direct assignment, shallow copy and deep copy of the case analysis"!
This paper gives an example of Python direct assignment, shallow copy and deep copy. Share with you for your reference, the details are as follows:
Direct assignment: it is actually a reference (alias) to the object.
Copy: copies the parent object, not the internal child objects of the object.
Deep copy (deepcopy): the deepcopy method of the copy module that completely copies the parent object and its children.
Dictionary shallow copy instance
Example
> a = {1: [1min2 a.copy () > a, b () > > a, b ({1: [1rem 2jue 3]}, {1: [1m 2jue 3]}) > > a [1] .append (4) > > a, b ({1: [1pr 2je 3,4]}, {1: [1pm 2jue 3,4]})
Deep copy requires the introduction of the copy module:
Example
> > 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]})
Analysis
B = a.copy (): shallow copy, an and b are separate objects, but their child objects still point to the unified object (which is a reference).
B = copy.deepcopy (a): deep copy, an and b completely copy the parent object and its children, and the two are completely independent.
More Instanc
The following examples are copy.copy (shallow copy) and (copy.deepcopy) using the copy module:
Example
#! / usr/bin/python#-*-coding:utf-8-*-import copya = [1, 2, 3, 4, ['await,' b']] # original object b = a # assignment, pass the reference of the object c = copy.copy (a) # object copy, shallow copy d = copy.deepcopy (a) # object copy Deep copy a.append (5) # modify object aa [4] .append ('c') # modify the array object print ('a =', a) print ('b =', b) print ('c =', c) print ('d =', d) in object a
The output of the above example is as follows:
('a =', [1, 2, 3, 4, ['a', 'baked,' c'], 5])
('b =', [1, 2, 3, 4, ['await,' baked,'c'], 5])
('c =', [1, 2, 3, 4, ['await,' baked,'c']])
('d =', [1, 2, 3, 4, ['await,' b']])
Thank you for your reading, the above is the content of "Python direct assignment, shallow copy and deep copy case analysis". After the study of this article, I believe you have a deeper understanding of the problem of Python direct assignment, shallow copy and deep copy case analysis, and the specific use still needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!