我有一个问题,我想递归地更改类中某些子元素的类。
我有一个可行的解决方案,如下:
class PerformanceAggregator:
def __init__(self, collection: pf.GenericPortfolioCollection):
self.collection = collection
self.change_children()
def __getattr__(self, item):
return getattr(self.collection, item, None)
def change_children(self):
for i in range(len(self.children)):
if isinstance(self.children[i], pf.GenericPortfolioCollection):
self.children[i] = PerformanceAggregator(self.children[i])
但是,change_children方法不是很Python。
会更好class PerformanceAggregator2:
def __init__(self, collection: pf.GenericPortfolioCollection):
self.collection = collection
self.change_children()
def __getattr__(self, item):
return getattr(self.collection, item, None)
def change_children(self):
for child in self.children:
if isinstance(child, pf.GenericPortfolioCollection):
child = PerformanceAggregator(child)
但是此方法无法正常工作。它不会像第一种方法那样替换“ child”元素。有人对出什么问题有想法吗?
当您遍历self.children时,您正在将child分配给PerformanceAggregator(child),但不一定更新self.children中的child元素。
这应该起作用:
def change_children(self): for (val,child) in enumerate(self.children): if isinstance(child, pf.GenericPortfolioCollection): self.children[val] = PerformanceAggregator(child)