python trick

1
2
3
4
5
6
7
8
9
def make_averager():
count = 0
total = 0

def averager(new_value):
count += 1
total += new_value
return total / count
return averager

对于数字,字符串,元祖 不可变类型来说,只能读取不能更新。 重新绑定会隐式创建局部变量count.
只有可变变量是可以的。

或者使用nonlocal count, total

请作者喝一杯咖啡☕️