Reference, Deep Copy and Shallow Copy
(unfinished) 引用、浅拷贝和深拷贝
Last updated
(unfinished) 引用、浅拷贝和深拷贝
Last updated
c = a 表示 c 和 a 指向相同的地址空间,并没有创建新的对象。在Python里,变量名永远都是reference,我们是把pass by reference.
d = copy.copy(a) 创建了一个新对象,复制了原有对象的引用。
对象复制(y=x)和浅复制(z=np.copy(x))一个list,list元素其实都是那些,所以x和yID相同,都指的同一片空间[1,2,3]。
e = copy.deepcopy(a) 新建了一个新对象,完整的在内存中复制原有对象。
上面这个例子,左图是
而右图是
使用深拷贝时,需要注意以下两个问题:
递归对象拷贝: Recursive objects (compound objects that, directly or indirectly, contain a reference to themselves) may cause a recursive loop.
大对象拷贝: Because deep copy copies everything it may copy too much, e.g., administrative data structures that should be shared even between copies.
以下是Python给的解释
The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):
A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
这个时候append完了以后是[10, 20, 30, [1, 2, 3, 4]] , 这是因为对mylist reference的对象上直接操作了。
但是,如果只是函数传值,传值后变量该是什么其实还是什么,传的只是变量指向的那个单元
再看两个例子
发生的是上图的操作,append了之后改变了funcA()
发生的是上图的事情