Python中的copy和deepcopy

基础

  1. ==在python中的成立条件是value相同
  2. is在python中的成立条件是id相同
  3. =是赋值运算符,可以创建目标和对象的绑定关系
  4. 复合对象是包含列表或类的实例等其他对象的对象
  5. 对于不可变对象,如字符串、元组和整数等,使用copydeepcopy是多余的,因为它们不可修改,所以不存在“深复制”或“浅复制”的问题。

使用

import copy
str1 = "str1"

str1_copy = copy.copy(str1)
str1_deep_copy = copy.deepcopy(str1)

差异

  1. 在非复合对象的使用上,两者作用相同,都是返回一个原对象的副本(id不同,修改不会改变原对象)
  2. 在复合对象的使用上,copy会将原始对象中的对象引用插入其中
  3. 在复合对象的使用上,deepcopy会将递归的将原始对象中的对象生成副本插入其中

例子

import copy

list1 = [1, 2, 3, 4, ['a', 'b']]

list2 = copy.copy(list1)
list3 = copy.deepcopy(list1)

print(list2, list3)
print(id(list1), id(list2), id(list3))
print((list1==list2), (list1==list3))
print((list1 is list2), (list1 is list3))
list2.append(5)
list3.append(6)
list1.append(7)
list1[0] = 0
# list1[4] = 999
list2[4].append(777)
print(list1, list2, list3)
print(id(list1), id(list2), id(list3))

# Here is output
[1, 2, 3, 4, ['a', 'b']] [1, 2, 3, 4, ['a', 'b']]
4365056832 4365056896 4365057024
True True
False False
[0, 2, 3, 4, ['a', 'b', 777], 7] [1, 2, 3, 4, ['a', 'b', 777], 5] [1, 2, 3, 4, ['a', 'b'], 6]
4365056832 4365056896 4365057024

猜你喜欢

转载自blog.csdn.net/majiayu000/article/details/132859066
今日推荐