nonlocal 声明: 将变量标记为自由变量
def make_averager():
"""计算移动平均值"""
series = []
def averager(new_value):
# series 是自由变量:指未在本地作用域中绑定的变量
series.append(new_value)
print(f'series : {series}')
total = sum(series)
return total/len(series)
return averager
avg = make_averager()
print(avg(10))
print(avg(11))
print(avg(12))
"""优化方案:
只存储目前的总值和元素个数,然后使用这个两个数计算均值
nonlocal 声明: 将变量标记为自由变量
"""
def make_averager():
"""计算移动平均值 优化版本"""
count = 0
total = 0
def averager(new_value):
nonlocal count, total
# 这里相当于隐形将count 变成了局部变量,引入nonlocal解决
count += 1
total += new_value
return total / count
return averager
avg2 = make_averager()
print(avg2(10))
print(avg2(11))
print(avg2(12))