我想创建一个类,它可以提供一个未被深拷贝的属性列表copy.deepcopy()
。例如像这样:
class CustomDeepcopy(object):
a = SomeSimpleObject()
b = SomeBigObject()
def dont_deepcopy(self):
return ['b']
def __deepcopy__(self,memo):
#Somehow call copy.deepcopy(self) and have it
#deepcopy self.a but not self.b
#
#For example, this *almost* works,
for attr in self.dont_deepcopy():
val = getattr(self,attr,None)
if val is not None:
memo[id(val)]=val
return copy.deepcopy(self,memo)
问题是我认为我不能copy.deepcopy()
从内部调用,__deepcopy__()
因为这会导致无限递归(因为copy.deepcopy()
首先检查我的对象是否有__deepcopy__()
方法)。有什么办法可以做到这一点吗?