好吧……这可能是个愚蠢的问题……但我现在找不到答案!
我需要实现一个对象的复制,我希望复制它的所有属性,除了一两个我想完全控制复制的属性。
这是对象的标准复制行为:
>>> class test(object):
... def __init__(self, arg):
... self._a = arg
...
>>> t = test(123999)
>>> t._a
123999
>>> tc = copy.copy(t)
>>> tc._a
123999
这基本上意味着所有的属性都被复制了。我想做的是以下列方式重新使用此行为:
>>> class test(object):
... def __init__(self, arga, argb):
... self._a = arga
... self._b = argb
...
... def __copy__(self):
... obj_copy = copy.copy(self) #NOT POSSIBLE OF COURSE => infinite recursion
... obj_copy._b = my_operation(obj_copy._b)
... return obj_copy
我希望你明白我的意思:我想重新使用对象复制行为,但 Hook 我自己的操作。有没有一种干净的方法来做到这一点(无需执行 for attr_name in dir(self): ...
)???
最佳答案
你可以这样做:
def __copy__(self):
clone = copy.deepcopy(self)
clone._b = some_op(clone._b)
return clone
这会起作用,因为 deepcopy
避免了递归。来自python docs :
The deepcopy() function avoids these problems by: keeping a “memo” dictionary of objects already copied during the current copying pass; and letting user-defined classes override the copying operation or the set of components copied.
关于Python 副本 : How to inherit the default copying behaviour?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3253439/