python中的深拷贝和浅拷贝

时间:2022-09-06 19:55:18
所谓浅拷贝就是对引用的拷贝,深拷贝就是对对象的内容的拷贝。
>>> person = ['name',['saving',100]]
>>> hubby = person[:]
>>> wifey = list(person)
>>> [id(x) for x in [person,hubby,wifey]]
[1933823305992, 1933823305544, 1933823587528]
>>> hubby[0]='joe'
>>> wifey[0]='jane'
>>> hubby,wifey
(['joe', ['saving', 100]], ['jane', ['saving', 100]])
>>> hubby[1][1]=50
>>> hubby,wifey
(['joe', ['saving', 50]], ['jane', ['saving', 50]])
以上我们修改了 hubby[1][1]=50 却发现我wifey中的数值也改变了,原因就是我们仅仅对person进行了浅拷贝。
序列类型对象的浅拷贝是默认类型的拷贝,可以以一下几种方式产生:1)完全切片[:]; 2)利用工厂函数,如list(); 3)copy模块中的copy()函数 

还有就是我们使 wifey[0]='jane', hubby[0]='joe'却没变成'jane', 是因为第一个对象是不可变的
要对person进行深拷贝我们需要引入copy模块
>>>import copy
>>> person = ['name',['saving',100]]
>>> hubby = person
>>> wifey = copy.deepcopy(person)
>>> [id(x) for x in [person,hubby,wifey]]
[1933823307144, 1933823307144, 1933823305992]
>>> hubby[0]='joe'
>>> wifey[0]='jane'
>>> hubby,wifey
(['joe', ['saving', 100]], ['jane', ['saving', 100]])
>>> hubby[1][1]=50
>>> hubby,wifey
(['joe', ['saving', 50]], ['jane', ['saving', 100]])

>>> [id(x) for x in hubby]
[1933823586232, 1933823308680]
>>> [id(x) for x in wifey]
[1933819414712, 1933823308424]
这就实现了深拷贝。

warning : 
    1)非容器类型(数字,字符串...)没有被拷贝一说,浅拷贝使用完全切片操作完成的
    2)如果元组变量只包含原子类型对象,对他的深拷贝不会进行
        >>> person = ['name',('saving',100)]
        >>> newPerson = copy.deepcopy(person)
        >>> [id(x) for x in [person,newPerson]]
        [1933823308552, 1933823306376]
        >>> [id(x) for x in person]
        [1933812079504, 1933819418632]
        >>> [id(x) for x in newPerson]
        [1933812079504, 1933819418632]

另:copy模块中只有copy()和deepCopy()两个函数可用