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