Python:浅层和深层副本构造函数的实现
在大多数情况下,由于有指针的概念,因此在C ++中易于实现复制构造函数(或重载的赋值运算符)。但是,我对如何在Python中实现浅层复制和深层复制感到很困惑。
It is in most of the situations easy to implement copy constructors (or overloaded assignment operator) in C++ since there is a concept of pointers. However, I'm quite confused about how to implement shallow and deep copy in Python.
我知道其中一个库中有特殊命令,但它们没有在自己编写的课程上工作。那么常见的实现方式是什么?
I know that there are special commands in one of the libraries but they don't work on classes that you have written by yourself. So what are the common ways to implement?
P.S。在某些基本数据结构(链接列表或树)上显示过程将受到赞赏。
P.S. Showing process on some basic data structures (linked list or tree) will be appreciated.
编辑:谢谢,他们工作了,这是我在语法上的错误。
我对使用 __ copy __()
和 __ deep_copy()__
覆盖这些功能非常感兴趣。例如。如何在不知道数据结构中包含哪种类型的信息的情况下进行深层复制?
Thanks, they worked, it was my mistake in syntax.
I am very interested in overwriting these functions with __copy__()
and __deep_copy()__
. For example. how can I make a deep copy without knowing which type of information is in a data structure?
python copy
模块可以重复使用 pickle
模块接口
The python copy
module can reuse the pickle
module interface for letting classes customize copy behaviour.
自定义类实例的默认设置是创建一个新的空类,换出 __ class __
属性,然后对于浅副本,只需使用原始值更新副本上的 __ dict __
即可。较深的副本将遍历 __ dict __
。
The default for instances of custom classes is to create a new, empty class, swap out the __class__
attribute, then for shallow copies, just update the __dict__
on the copy with the values from the original. A deep copy recurses over the __dict__
instead.
否则,您指定 __ getstate __( )
方法返回内部状态。这可以是您的类 __ setstate __()
可以再次接受的任何结构。
Otherwise, you specify a __getstate__()
method to return internal state. This can be any structure that your class __setstate__()
can accept again.
您还可以指定 __ copy __()
和/或 __ deepcopy __()
方法来控制 just 复制行为。这些方法有望自己完成所有复制, __ deepcopy __()
方法将传递给备忘录映射,以传递给递归的 deepcopy()
呼叫。
You can also specify the __copy__()
and/or __deepcopy__()
methods to control just copy behaviour. These methods are expected to do all the copying themselves, the __deepcopy__()
method is passed a memo mapping to pass on to recursive deepcopy()
calls.
例如:
from copy import deepcopy
class Foo(object):
def __init__(self, bar):
self.bar = bar
self.spam = expression + that * generates - ham # calculated
def __copy__(self):
# self.spam is to be ignored, it is calculated anew for the copy
# create a new copy of ourselves *reusing* self.bar
return type(self)(self.bar)
def __deepcopy__(self, memo):
# self.spam is to be ignored, it is calculated anew for the copy
# create a new copy of ourselves with a deep copy of self.bar
# pass on the memo mapping to recursive calls to copy.deepcopy
return type(self)(deepcopy(self.bar, memo))
此示例定义了自定义复制挂钩,以防止 self.spam
也被复制,新实例将对其进行重新计算。
This example defines custom copy hooks to prevent self.spam
being copied too, as a new instance will calculate it anew.