深层复制覆盖说明
deepcopy override clarification
在"How to override the copy/deepcopy operations for a Python object?"post中,其中一个答案是这样写的:
def __deepcopy__(self, memo):
cls = self.__class__
result = cls.__new__(cls)
memo[id(self)] = result
for k, v in self.__dict__.items():
setattr(result, k, deepcopy(v, memo))
return result
是覆盖深度复制方法的一种可能方式。我不明白每一行的作用。这个实现的目的是什么?我不能像下面这样使用特定于我的 class 的内容创建自己的复制方法吗?
def my_copy(self, original_obj):
obj = MyClass()
obj.a = (copy of a from the other object)
obj.b = (copy of b from the other object)
...
return obj
你是对的,你可以按照你介绍的方式做到这一点。但是,这将特定于您的对象实现。您发布的示例更为通用,可以处理复制许多不同的 classes 对象。它也可以作为 mixin 来轻松添加到你的 class.
提供的代码,执行此操作:
def __deepcopy__(self, memo):
cls = self.__class__ # Extract the class of the object
result = cls.__new__(cls) # Create a new instance of the object based on extracted class
memo[id(self)] = result
for k, v in self.__dict__.items():
setattr(result, k, deepcopy(v, memo)) # Copy over attributes by copying directly or in case of complex objects like lists for exaample calling the `__deepcopy()__` method defined by them. Thus recursively copying the whole tree of objects.
return result
另请注意,如果您的 class 由列表等复杂属性组成,您还需要直接对它们调用 deepcopy,否则您最终会得到一些属性的浅拷贝。
编辑
memo
是一个字典,其中保留了 id 到对象的对应关系,以完美地重建复杂的对象图。
在"How to override the copy/deepcopy operations for a Python object?"post中,其中一个答案是这样写的:
def __deepcopy__(self, memo):
cls = self.__class__
result = cls.__new__(cls)
memo[id(self)] = result
for k, v in self.__dict__.items():
setattr(result, k, deepcopy(v, memo))
return result
是覆盖深度复制方法的一种可能方式。我不明白每一行的作用。这个实现的目的是什么?我不能像下面这样使用特定于我的 class 的内容创建自己的复制方法吗?
def my_copy(self, original_obj):
obj = MyClass()
obj.a = (copy of a from the other object)
obj.b = (copy of b from the other object)
...
return obj
你是对的,你可以按照你介绍的方式做到这一点。但是,这将特定于您的对象实现。您发布的示例更为通用,可以处理复制许多不同的 classes 对象。它也可以作为 mixin 来轻松添加到你的 class.
提供的代码,执行此操作:
def __deepcopy__(self, memo):
cls = self.__class__ # Extract the class of the object
result = cls.__new__(cls) # Create a new instance of the object based on extracted class
memo[id(self)] = result
for k, v in self.__dict__.items():
setattr(result, k, deepcopy(v, memo)) # Copy over attributes by copying directly or in case of complex objects like lists for exaample calling the `__deepcopy()__` method defined by them. Thus recursively copying the whole tree of objects.
return result
另请注意,如果您的 class 由列表等复杂属性组成,您还需要直接对它们调用 deepcopy,否则您最终会得到一些属性的浅拷贝。
编辑
memo
是一个字典,其中保留了 id 到对象的对应关系,以完美地重建复杂的对象图。