nonlocal 声明: 将变量标记为自由变量

    1. def make_averager():
    2. """计算移动平均值"""
    3. series = []
    4. def averager(new_value):
    5. # series 是自由变量:指未在本地作用域中绑定的变量
    6. series.append(new_value)
    7. print(f'series : {series}')
    8. total = sum(series)
    9. return total/len(series)
    10. return averager
    11. avg = make_averager()
    12. print(avg(10))
    13. print(avg(11))
    14. print(avg(12))
    15. """优化方案:
    16. 只存储目前的总值和元素个数,然后使用这个两个数计算均值
    17. nonlocal 声明: 将变量标记为自由变量
    18. """
    19. def make_averager():
    20. """计算移动平均值 优化版本"""
    21. count = 0
    22. total = 0
    23. def averager(new_value):
    24. nonlocal count, total
    25. # 这里相当于隐形将count 变成了局部变量,引入nonlocal解决
    26. count += 1
    27. total += new_value
    28. return total / count
    29. return averager
    30. avg2 = make_averager()
    31. print(avg2(10))
    32. print(avg2(11))
    33. print(avg2(12))