您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python:浅层和深层副本构造函数的实现

Python:浅层和深层副本构造函数的实现

pythoncopy模块可以重用pickle模块接口,以使类自定义复制行为。

自定义类实例认值是创建一个新的空类,换出__class__属性,然后对于浅表副本,只需__dict__使用原始值更新副本中的即可。较深的副本将__dict__代替副本。

否则,您将指定一种__getstate__()返回内部状态的方法。这可以是您的班级__setstate__()可以再次接受的任何结构。

您还可以指定__copy__()和/或__deepcopy__()方法 控制复制行为。这些方法有望自己完成所有复制,该__deepcopy__()方法将传递给备注映射以传递给递归deepcopy()调用

例如:

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复制,因为新实例将重新对其进行计算。

python 2022/1/1 18:42:31 有283人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶