我有一个问题,我想递归地更改类中某些子元素的类。
我有一个可行的解决方案,如下所示:
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”元素。有人知道哪里出了问题吗?
答案 0 :(得分:1)
当您遍历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)