使用深拷贝实现递归
我该如何在深拷贝函数对象中实现递归?以下是相关的代码(如果你需要更多,请告诉我):
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 个回答
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)