Python copy object

巴扎黑
巴扎黑Original
2017-05-21 10:58:221357browse

When assigning values ​​between objects in Python, they are passed by reference. If you need to copy an object, you need to use the copy module in the standard library.

1. copy.copy shallow copy only copies the parent object, and does not copy the internal child objects of the object.
2. copy.deepcopy deep copy copies the object and its sub-objects
A good example:

import copy
a
= [1, 2, 3, 4, ['a', 'b']] # Original object

b
= a #Assignment, passing 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 a
##a[
4].append('c') #Modify the ['a', 'b'] array object in object a

print
'a = ', aprint 'b = ', b
print 'c = ', c
print 'd = ', d


Output 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']]

The above is the detailed content of Python copy object. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn