Introduction:
This blog mainly discusses the problem of copying Python objects, distinguishing between shallow copy and deep copying. To keep track of objects in memory, Python uses the simple technique of reference counting, which is briefly described below.
1. Reference count:
When an object is created and assigned to a variable, the object's reference count is set to 1. When the same object is assigned to another variable, or passed as a parameter to a function, method, or class instance, or is assigned a member of a Window object, a new reference (or alias) for that object is created, and the reference count of the object is added 1. Use the DEL keyword to reduce the reference count.
We can see the following code:
#!/usr/bin/env pythonimport3.14print‘x ‘, id(x), sys.getrefcount(x)y = xprint‘y ‘3.14print‘z ‘, id(z), sys.getrefcount(z)del xprint‘PI‘, id(3.14), sys.getrefcount(3.14)
The output is as follows:
x 346457124y 346457125z 346457126PI346457125
We see that although the reference count changes in the same way as we imagined, but the value is a bit different, for this phenomenon, the Python official website gives the explanation:
thereferencecountofthecountisitthereferenceasto getrefcount().
2. Copy:
From the previous we can know that the object assignment is actually a simple object reference, the copy operation can import the Python copy module and call the built-in function to complete, see the following code:
#!/usr/bin/env pythonimport copydef print_(arg): print id(arg),arg,‘---‘,id(arg[2]),arg[2]a = [‘123‘‘456‘, [123,456]]b = ac = copy.copy(a)d = copy.deepcopy(a)a.append(‘789‘); a[2].insert(2,789) // 修改列表print_(a); print_(b); print_(c); print_(d)
The output is as follows:
140694526889784[' 123 ',' 456 ', [123,456,789],' 789 '] ---140694526920680[123,456,789]140694526889784[' 123 ',' 456 ', [123,456,789],' 789 '] ---140694526920680[123,456,789]140694527025592[' 123 ',' 456 ', [123,456,789]] ---140694526920680[123,456,789]140694526919672[' 123 ',' 456 ', [123,456]] ---140694527027464[123,456]
There are a few things to note about references:
1) Non-container types (such as numbers, strings, and other "atomic" types of objects, such as code, types, and Xrange objects, etc.) do not have a copy.
2) If a tuple variable contains only an atomic type object, a deep copy of it will not be made, that is, the deep copy is also a shallow copy at this time.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Python Programming Learning--copy