Python programming learning-copy
Introduction:
This blog mainly discusses the copying of Python objects, which distinguishes between shallow copy and deep copy. To keep track of objects in the memory, Python uses the reference count simple technology, which is described below.
1. Reference count:
When an object is created and assigned a value to a variable, the reference count of the object is set to 1. When the same object is assigned to another variable, or is passed as a parameter to a function, method, or class instance, or is assigned as a member of a window object, A new reference (or alias) of this object is created, and the reference count of this object is increased by 1. The del keyword can be used to reduce the reference count.
We can see the following code:
#!/usr/bin/env pythonimport sysx = 3.14print 'x ', id(x), sys.getrefcount(x)y = xprint 'y ', id(y), sys.getrefcount(y)z = 3.14print 'z ', id(z), sys.getrefcount(z)del xprint 'PI', id(3.14), sys.getrefcount(3.14)
The output is as follows:
x 34645712 4y 34645712 5z 34645712 6PI 34645712 5
We can see that although the change in reference count is the same as we thought, the value is a bit different. For this phenomenon, the Python official website provides an explanation:
sys.getrefcount(object)Return the reference count of the object. The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to getrefcount().
2. Copy:
As we can see earlier, object assignment is actually a simple object reference. The copy operation can import the copy module of Python and call the built-in function. For details, see the following code:
#! /Usr/bin/env pythonimport copydef print _ (arg): print id (arg), arg, '---', id (arg [2]), arg [2] a = ['20140901', '20160901', [123] B = ac = copy. copy (a) d = copy. deepcopy (a). append ('20140901'); a [2]. insert (2,789) // modify the 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]
Note the following points for reference:
1) Non-container type (such as numbers, strings, and other "Atomic" objects, such as code, type, and xrange objects.
2) If the tuples only contain atomic objects, deep copy is not performed. That is, deep copy is also a shortest copy.