支持自定义类的深层复制操作?

Pie*_*rre 5 python copy

我有一个dict子类,它添加了新的方法和功能,我想要支持的主要内容是递归更新,它通过逐个更新每个嵌套dict来实现,与dict.update方法不同.

我正在使用该copy.deepcopy函数,就像任何其他对象一样,问题是当我向这个类添加属性访问时它不起作用:

__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
Run Code Online (Sandbox Code Playgroud)

现在我收到这个错误:

KeyError: '__deepcopy__'
Run Code Online (Sandbox Code Playgroud)

copy.deepcopy函数正在尝试__deepcopy__对此对象使用方法:

copier = getattr(x, "__deepcopy__", None)
Run Code Online (Sandbox Code Playgroud)

为什么添加后__getattr__发生这种情况?有没有办法解决它而不实现__deepcopy__方法?


我从来没有使用过这种__deepcopy__方法所以我尝试添加一个,这就是我所拥有的:

def __deepcopy__(self, memo):
    # create a new instance of this object
    new_object = type(self)()

    # iterate over the items of this object and copy each one
    for key, value in self.iteritems():
        new_object[key] = copy.deepcopy(value, memo)

    return new_object
Run Code Online (Sandbox Code Playgroud)

这是正确的实施方式__deepcopy__吗?

int*_*jay 3

你不需要__deepcopy__在这里实现。

问题是你__getattr__总是调用__getitem__,这会引发一个KeyError不存在的属性。但__getattr__预计在这种情况下会提高AttributeError

的实现getattr捕获了AttributeError,但没有捕获KeyError,因此异常未被处理。

在这种情况下,你应该改变__getattr__以正确加注AttributeError