在方法[duplicate]中的for循环中更改实例属性

问题描述 投票:0回答:1

我有一个问题,我想递归地更改类中某些子元素的类。

我有一个可行的解决方案,如下:

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”元素。有人对出什么问题有想法吗?

python class for-loop instance-variables
1个回答
0
投票

当您遍历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)
© www.soinside.com 2019 - 2024. All rights reserved.