使用深层副本实现递归

时间:2011-06-08 00:24:31

标签: python pickle distributed-computing deep-copy

如何在深层复制功能对象中实现递归?这是相关的代码(如果你想要更多请问): PS:我希望递归迭代一个过滤的引用列表。目标是下载并插入任何丢失的对象。

copy.py

from put import putter

class copier:
  def __init__(self, base):
    self.base = base
  def copyto(self, obj):
    put = putter(obj)
    for x in self.base.__dict__:
      put(x)

put.py

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

1 个答案:

答案 0 :(得分: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)