Example Analysis of reference and replication usage in python and Analysis of python instances
This example describes how to reference and copy data in python. Share it with you for your reference. The specific analysis is as follows:
In python, any immutable object transmits values, while a mutable object transmits references.
Whether it is passing parameters to a function or copying any form of object, immutable objects (such as integers and strings) are actually copied, while mutable objects only copy a reference to them, that is, there is only one copy of the object in the memory, and two copies are referenced.
A = B will create a reference to B. For immutable objects such as numbers and strings, this assignment actually creates a copy of B.
>>> a='hello'>>> b=a>>> id(a)29326432>>> id(b)29326432>>> b is aTrue>>> a=1000>>> b'hello'
For mutable objects, such as dictionaries and lists, a and B reference the same object. modifying any of these variables will affect the other.
>>> a=[1,2,3,4]>>> b=a>>> id(a)29280896>>> id(b)29280896>>> b[3]='ccccccccc'>>> a[1, 2, 3, 'ccccccccc']>>>
List and dictionary container objects can be assigned with two assignment operations: shallow copy and deep copy. Create a new object in the shortest copy, but it contains references to the items contained in the original object.
For example:
>>> A = [1, 2, 4, [9, 0] >>> B = a >>> a = [1, 2, 3, 4, [1000] >>> B = list (a) >>> B is aFalse >>> B [0] = 1000 >>> B [, 2, 3, 4, [9, 0] # Note: After B is modified to B [0], it does not affect a >>> a [1, 2, 3, 4, [9, 0]> B [4] [1] = 'cccc' # Note: After B modifies B [4] [1, impact on a> B [1000, 2, 3, 4, [9, 'cccccc']> a [1, 2, 3, 4, [9, 'cccc']
Deep copy creates a new object and Recursively copies all the objects it contains. You can use the copy. deepcopy () function to create deep copy without built-in objects.
>>> Import copy >>> a = [, 3, [] >>> B = copy. deepcopy (a) >>> id (B) 29582240 >>> id () 29581840 >>> a is bFalse >>> B [0] = 1000 >>> B [1000, 2, 3, [4, 5] # note that modification of B [0] does not affect a> a [1, 2, 3, [4, 5]> B [3] [1] = 'gggggg'> B [1000, 2, 3, [4, 'gggggg'] # After B [3] [1] is modified, it has no effect on a, which is different from that of light replication> a [1, 2, 3, [4, 5]
I hope this article will help you with Python programming.