我想創建一個類,它可以提供一個屬性列表,它不會被copy.deepcopy()
深度覆蓋。例如像這樣:在Python中,如何在我的__deepcopy __()實現中調用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)
的問題是,我不認爲我可以從__deepcopy__()
內調用copy.deepcopy()
,因爲這會導致無窮遞歸(因爲copy.deepcopy()
首先檢查我的對象有一個__deepcopy__()
方法)。有什麼辦法可以做到這一點?
爲什麼你叫'和'self' deepcopy'作爲第一個參數 – Blender
因爲我想'__deepcopy __()'方法返回的'一個deepcopy的自我「,以sm爲模所有改變,我不深'複製'self.b'。 – marius
'deepcopy'只有一個參數。你是淺拷貝它們嗎? – Blender