1.在python中,对象赋值实际上是对象的引用。当创建一个对象,然后把它赋给另一个变量的时候,python并没有拷贝这个对象,而只是拷贝了这个对象的引用
(1)直接赋值,默认浅拷贝传递对象的引用而已,原始列表改变,被赋值的b也会做相同的改变
# -*- coding: utf-8 -*-if __name__ == '__main__':b = [1, 2, 3]a = bprint(a)print(b)a.append(4)print(a)print(b)
(2)copy浅拷贝,没有拷贝子对象,所以原始数据改变,子对象会改变
# -*- coding: utf-8 -*-
import copyif __name__ == '__main__':b = [1, 2, ["hello", "word"]]a = copy.copy(b)print(a)print(b)a.append(4)print(a)print(b)b[2].append("鸿蒙2.0")print(a)print(b)
运行结果:
"C:\Program Files\Python38\python.exe" E:/PythonSourceCode/test/main.py
[1, 2, ['hello', 'word']]
[1, 2, ['hello', 'word']]
[1, 2, ['hello', 'word'], 4]
[1, 2, ['hello', 'word']]
[1, 2, ['hello', 'word', '鸿蒙2.0'], 4] 这里数据变了
[1, 2, ['hello', 'word', '鸿蒙2.0']]
(3)深拷贝,包含对象里面的自对象的拷贝,所以原始对象的改变不会造成深拷贝里任何子元素的改变
# -*- coding: utf-8 -*-
import copyif __name__ == '__main__':b = [1, 2, ["hello", "word"]]a = copy.deepcopy(b)print(a)print(b)b[2].append("鸿蒙2.0")print(a)print(b)
运行结果:
"C:\Program Files\Python38\python.exe" E:/PythonSourceCode/test/main.py
[1, 2, ['hello', 'word']]
[1, 2, ['hello', 'word']]
[1, 2, ['hello', 'word']]
[1, 2, ['hello', 'word', '鸿蒙2.0']]