2011-06-08 152 views
2

如何在深拷貝函數對象中實現遞歸?這是相關的代碼(如果你想要更多,請詢問): PS:我希望遞歸遍歷經過篩選的引用列表。目標是下載並插入任何缺失的對象。使用深層副本實現遞歸

copy.py

​​

put.py

class putter: 
    def __init__(self, parent): 
    self.parent = parent 
    def put(self, name, obj): 
    self.parent.__dict__[name] = obj 
+7

問題是什麼? – 2011-06-08 00:26:13

+0

@Simon等人,請參閱編輯。 – motoku 2011-06-08 00:28:30

+1

你想遞歸完成什麼? – Doug 2011-06-08 00:32:40

回答

2

檢查出copy.deepcopy的文件,如果你能實現你想要__getinitargs__()__getstate__()__setstate__(),然後,將節省您什麼很多悲傷。否則,你將需要自己重新實現它,它應該看起來像這樣:

def deepcopyif(obj, shouldcopyprop): 
    copied = {} # Remember what has already been copied 
    def impl(obj): 
     if obj in copied: 
      return copied[obj] 
     newobj = *** Create a copy *** 
     copied[obj] = newobj # IMPORTANT: remember the new object before recursing 
     for name, value in obj.__dict__: # or whatever... 
      if shouldcopyprop(obj.__class__, name): # or whatever 
       value = impl(value) # RECURSION: this will copy the property value 
      newobj.__dict__[prop] = value 
     return newobj 
    return impl(obj)