我不明白为什么我可以在这里使用系列变量:
def calculate_mean():
series = []
def mean(new_value):
series.append(new_value)
total = sum(series)
return total/len(series)
return mean
但我不能在这里使用计数和总数变量(赋值前引用的变量):
def calculate_mean():
count = 0
total = 0
def mean(value):
count += 1
total += value
return total/count
return mean
只有当我使用这样的非本地关键字时它才有效:
def calculate_mean():
count = 0
total = 0
def mean(value):
nonlocal count, total
count += 1
total += value
return total/count
return mean
这就是我使用 calculate_mean() 的方式
mean = calculate_mean()
print(mean(5))
print(mean(6))
print(mean(7))
print(mean(8))