使用深拷贝实现递归

发布于 2024-11-14 02:12:06 字数 476 浏览 6 评论 0原文

如何在深拷贝函数对象中实现递归?这是相关代码(如果您想要更多,请询问): 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)

放置.py

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

How can I implement recursion in a deep copy function object? This is the relevant code (if you want more then please ask):
PS: I would like the recursion to iterate through a filtered list of references. The goal is to download and insert any missing objects.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

桃酥萝莉 2024-11-21 02:12:06

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

Check out the documentation for copy.deepcopy, if you can implement what you want with __getinitargs__(), __getstate__() and __setstate__(), then that will save you a lot of grief. Otherwise, you will need to reimplement it yourself, it should look something like:

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文