1, a simple shared references:
python built a small integer constant pool and a string constant pool, the same number or string in a range of different variables are assigned to these different variables are pointing to the same memory address, which is called the shared references, a few simple examples:
Pass a simple variable is actually a shared references:
2, the dictionary copy () method
Dictionary of copy () method is equivalent to a dark copy, the original dictionary dic1 about to copy the contents of a dictionary to another dictionary exactly the same variable dic2, dic1 and content identical dic2, but different memory addresses are not shared references, which either make a change, the other party will not be affected, for example:
3, two kinds of methods copy copy module: copy.copy () and copy.deepcopy ()
First import module copy, import copy
copy.copy () method: copy mode with the copy () of the parameters relating to the type, copy only the outermost layer (sometimes nested), of the type comprising a variable parameter and the type of immutable type
1, the variable type: When a parameter is a variable type, which is executed as the outermost depth of replication, different addresses before and after the two variables, i.e. copy, if the original variable variable-type element is nested, then, the inner layer is a shallow copy, change one of the other affected. (I.e., two variables have different addresses, but refer to the same block of memory)
2, immutable: when copy () parameters are immutable, perform a shallow copy outermost layer (i.e., the same two variables refer to the same address, and a memory area), the inner layer will perform a shallow copy
copy.deepcopy (): Regardless of whether the parameter is a variable type, a deep copy is performed recursively, if the variable variable variable or invariable nested, regardless of the depth of the inner or outer layers are performed replication when replicating (one case except), that is to open up another piece of memory space, all the contents of the original copy of the variables are over, assigned to a new variable, two variables though the same content, but with different addresses, and point to different areas, either to make content change, the other will not be affected.
注意:
在使用copy.deepcopy()方法时,如果参数为不可变类型,且里面嵌套的对象也是不可变类型,则此方法复制的结果为浅复制(即地址相同)。
作者:LittlePy
链接:https://www.jianshu.com/p/0394be0247db
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。