这段python代码中用了字典的嵌套,为什么同一个变量输出结果会不一样?感觉第二个输出的结果里最后一组数值,把前面的数值都覆盖了。不知道是为什么。怎么样才能在第二个输出里得到每一组的正确数值。
class Backtest:
def __init__(self, n) -> None:
self.n:int =3
self.atr_list:dict[str, dict]={}
self.atrs:dict[str, dict]={}
def run_testing(self):
for product in ['apple','orange','banana','lemon']:
self.sample_group(product,self.n)
self.n += 1
print("在结束遍历后的输出",self.atr_list)
def sample_group(self, product, qty):
for j in ['a','b','c','d','e','f',]:
self.atrs[j]= qty/1317
self.atr_list[product] = self.atrs
print("在遍历中逐个水果输出结果",product, self.atrs)
if __name__ == "__main__":
a=Backtest(10)
a.run_testing()
在方法sample_group中每次输出的self.atrs是这样的:
但在run_testing 方法中输出的结果却是这样的: