【问题标题】:Implementing recursion with a deep copy使用深拷贝实现递归
【发布时间】:2011-06-08 00:24:30
【问题描述】:

如何在深拷贝函数对象中实现递归?这是相关代码(如果您想要更多,请询问): PS:我希望递归遍历过滤的引用列表。目标是下载并插入任何丢失的对象。

复制.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

【问题讨论】:

  • 有什么问题?
  • 你希望递归完成什么?
  • 那么,我们已经将一只鸡和一只水母杂交,得到了能产生能产卵的息肉的卵?你想完成什么?
  • @thasc 和 lysdexia,我希望递归遍历过滤的引用列表。目标是下载并插入任何丢失的对象。
  • put 是一个 putter 实例。你的意思是put = putter(obj).put?。首先编写一些测试是一个真的好主意

标签: python pickle distributed-computing deep-copy


【解决方案1】:

查看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)

【讨论】:

    猜你喜欢
    • 2016-12-03
    • 2015-06-12
    • 2015-08-23
    • 2013-03-19
    • 2012-05-26
    • 2012-02-20
    • 2012-04-12
    • 2015-01-13
    • 2011-09-05
    相关资源
    最近更新 更多