class Averager1():
'''计算移动平均值的类第一种写法'''
def __init__(self):
self.series = []
def __call__(self,new_value):
self.series.append(new_value)
total = sum(self.series)
return total/len(self.series)
# avg1 = Averager1()
# print(avg1(10))
# print(avg1(11))
# print(avg1(12))
def make_averager():
'''计算移动平均值的类第二种写法(闭包)'''
series = [] #自由变量,历史数据保存在avg1.__closure__[0].cell_contents 中
def averager(new_value):
series.append(new_value)
total = sum(series)
return total/len(series)
return averager
avg1 = make_averager()
print(avg1(10))
print(avg1(11))
print(avg1(12))
def make_averager1():
'''计算移动平均值的类第三种写法(nonlocal)不保存所有历史,提高效率'''
count = 0
total = 0
def averager(new_value):
nonlocal count,total #把变量标记为自由变量,不会因为不可变类型而变成局部变量而不保存在闭包中
count +=1
total += new_value
return total/count
return averager
avg1 = make_averager1()
print(avg1(10))
print(avg1(11))
print(avg1(12))