非本地关键字如何工作?

How nonlocal keyword works?

在下面的代码中,

def makeAverage():
    series = []
    def average(newValue):
        series.append(newValue)
        total = sum(series)
        return total/len(series)
    return average

python 解释器不期望 seriesaverage().

中是 nonlocal

但是在下面的代码中

def makeAverage():
    count = 0
    total = 0
    def average(newValue):
        nonlocal count, total
        count += 1
        total += newValue
        return total/count
    return average

问题:

为什么 python 解释器期望 count & totalaverage() 中声明 nonlocal

如果您在该函数的任何地方 赋值给它并且您没有标记它(使用 globalnonlocal).在您的第一个示例中,average 内没有对 series 的赋值,因此它不被视为 average 的本地版本,因此使用了封闭函数的版本。在第二个示例中,average 中有对 totalcount 的赋值,因此需要将它们标记为 nonlocal 以从封闭函数访问它们。 (否则你会得到一个 UnboundLocalError 因为 average 试图在第一次分配给它们之前读取它们的值。)