2011-06-08 97 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)