当年话下
当前,最重要的限制是您不能分配给外部作用域变量。换句话说,闭包是只读的:>>> def outer(x): ... def inner_reads():... # Will return outer's 'x'.... return x... def inner_writes(y):... # Will assign to a local 'x', not the outer 'x'... x = y... def inner_error(y):... # Will produce an error: 'x' is local because of the assignment,... # but we use it before it is assigned to.... tmp = x... x = y... return tmp... return inner_reads, inner_writes, inner_error... >>> inner_reads, inner_writes, inner_error = outer(5)>>> inner_reads()5>>> inner_writes(10)>>> inner_reads()5>>> inner_error(10)Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 11, in inner_errorUnboundLocalError: local variable 'x' referenced before assignment除非另行声明,否则在本地范围(函数)中分配给它的名称始终是本地名称。尽管存在“全局”声明来声明变量全局变量(即使已将其分配给它),但对于封闭变量来说尚无此类声明。在Python 3.0中,有(将有)“ nonlocal”声明可以做到这一点。您可以同时使用可变的容器类型来解决此限制:>>> def outer(x):... x = [x]... def inner_reads():... # Will return outer's x's first (and only) element.... return x[0]... def inner_writes(y):... # Will look up outer's x, then mutate it. ... x[0] = y... def inner_error(y):... # Will now work, because 'x' is not assigned to, just referenced.... tmp = x[0]... x[0] = y... return tmp... return inner_reads, inner_writes, inner_error... >>> inner_reads, inner_writes, inner_error = outer(5)>>> inner_reads()5>>> inner_writes(10)>>> inner_reads()10>>> inner_error(15)10>>> inner_reads()15