python直接赋值、copy与deepcopy()
@toc
直接赋值
numbers=[1,2,3,4,5,6]
new_numbers=numbers
new_numbers[0]=9
print("numbers:",numbers)
print("ID of numbers:",id(numbers))#id()获取对象的内存地址
print("new_numbers:",new_numbers)
print("ID of new_numbers:",id(new_numbers))
运行结果
numbers: [9, 2, 3, 4, 5, 6]
ID of numbers: 140677220832008
new_numbers: [9, 2, 3, 4, 5, 6]
ID of new_numbers: 140677220832008#内存地址是同一个
直接赋值:其实就是对象的引用(别名),赋值的两个对象还是同一个对象
copy.copy()与copy.deepcopy()
old_list=[1,[2,3,4,5,6]]
new_list=copy.copy(old_list)
pro_list=copy.deepcopy(old_list)
new_list[1].append(7)
print("old_list:",old_list," ","id of old_list:",id(old_list))
print("new_list:",new_list," ","id of new_list:",id(new_list))
print("pro_list:",pro_list," ","id of new_list:",id(pro_list))
运行结果
old_list: [1, [2, 3, 4, 5, 6, 7]] id of old_list: 139991509315848
new_list: [1, [2, 3, 4, 5, 6, 7]] id of new_list: 139991538848776
pro_list: [1, [2, 3, 4, 5, 6]] id of new_list: 139991509317000
copy.copy() 浅拷贝, a 和 b 是一个独立的对象,但他们的子对象还是指向统一对象(是引用)。
copy.deepcopy() 深度拷贝, a 和 b 完全拷贝了父对象及其子对象,两者是完全独立的。