In Python 3.x, you can use the nonlocal
declaration (in nested
) to tell Python you mean to assign to the count
variable in nesting
.
In Python 2.x, you simply can't assign to count
in nesting
from nested
. However, you can work around it by not assigning to the variable itself, but using a mutable container:
def nesting():
count = [0]
def nested():
count[0] += 1
for i in range(10):
nested()
print count[0]
Although for non-trivial cases, the usual Python approach is to wrap the data and functionality in a class, rather than using closures.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…