📜  类的浅拷贝和深拷贝的区别

📅  最后修改于: 2021-09-15 02:01:16             🧑  作者: Mango

浅复制:浅重复更快。然而,它处理指针和引用是“懒惰的”。它不是创建指针指向的特定知识的当代副本,而是简单地复制指针价格。因此,每个第一个以及副本都可以具有引用常量基础知识的指针。

深度复制:深度重复真正克隆了底层数据。它不在第一个和副本之间共享。

下面是浅拷贝和深拷贝之间的表格区别:

Shallow Copy Deep Copy
Shallow Copy stores the references of objects to the original memory address.    Deep copy stores copies of the object’s value.
Shallow Copy reflects changes made to the new/copied object in the original object. Deep copy doesn’t reflect changes made to the new/copied object in the original object.
Shallow Copy stores the copy of the original object and points the references to the objects. Deep copy stores the copy of the original object and recursively copies the objects as well.
Shallow copy is faster. Deep copy is comparatively slower.

下面是解释类的浅拷贝和深拷贝的程序。

Python3
# Python3 implementation of the Deep
# copy and Shallow Copy
from copy import copy, deepcopy
 
# Class of Car
class Car:
  def __init__(self, name, colors):
     
     self.name = name
     self.colors = colors
     
honda = Car("Honda", ["Red", "Blue"])
 
# Deepcopy of Honda
deepcopy_honda = deepcopy(honda)
deepcopy_honda.colors.append("Green")
print(deepcopy_honda.colors, \
      honda.colors)
 
# Shallow Copy of Honda
copy_honda = copy(honda)
 
copy_honda.colors.append("Green")
print(copy_honda.colors, \
      honda.colors)


输出:
['Red', 'Blue', 'Green'] ['Red', 'Blue']
['Red', 'Blue', 'Green'] ['Red', 'Blue', 'Green']