1、赋值、浅拷贝和深拷贝
对于非容器类型(组合类型),如数字、字符,以及其他的“原子”类型,没有拷贝一说,产生的都是原对象的引用。
赋值:对原对象的引用,与原对象指向同一片内存地址。对原对象/子对象的改变都会同步。
浅拷贝(仅拷贝1层):创建新的对象,内容为对原对象第一层对象的引用。开辟新的空间,存放原对象第一层每个元素的地址。
深拷贝:创建新的对象,递归的拷贝原对象所包含的子对象。深拷贝出来的对象与原对象没有任何关联。
三者的具体区别看下面的例子:
import copy if __name__ == "__main__": # assign a1 = [1, 2, ["python", "hello"]] b1 = a1 a1.append(5) a1[2].append("world") print(a1) print(b1) ''' [1, 2, ['python', 'hello', 'world'], 5] [1, 2, ['python', 'hello', 'world'], 5] ''' # shallow copy a2 = [1, 2, ["python", "hello"]] b2 = copy.copy(a2) a2.append(5) a2[2].append("world") print(a2) print(b2) ''' [1, 2, ['python', 'hello', 'world'], 5] [1, 2, ['python', 'hello', 'world']] ''' # deep copy a3 = [1, 2, ["python", "hello"]] b3 = copy.copy(a3) a3.append(5) a3[2].append("world") print(a3) print(b3) ''' [1, 2, ['python', 'hello', 'world'], 5] [1, 2, ['python', 'hello']] '''