在方法中的 for 循环中更改实例属性
Changing instance attributes in for loop in method
我有一个问题,我想递归地更改 class 中某些子元素的 class。
我有一个可行的解决方案,如下所示:
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 方法不是很 pythonic。
会更好
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 时,您将子元素分配给 PerformanceAggregator(child) 但不一定更新 self.children 中的子元素。
这应该有效:
def change_children(self):
for (val,child) in enumerate(self.children):
if isinstance(child, pf.GenericPortfolioCollection):
self.children[val] = PerformanceAggregator(child)
我有一个问题,我想递归地更改 class 中某些子元素的 class。
我有一个可行的解决方案,如下所示:
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 方法不是很 pythonic。
会更好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 时,您将子元素分配给 PerformanceAggregator(child) 但不一定更新 self.children 中的子元素。
这应该有效:
def change_children(self):
for (val,child) in enumerate(self.children):
if isinstance(child, pf.GenericPortfolioCollection):
self.children[val] = PerformanceAggregator(child)