如何在嵌套函数中改变外层函数的变量
我想在一个嵌套函数里面修改一个变量,这个变量是在外面的函数里定义的,类似这样:
def nesting():
count = 0
def nested():
count += 1
for i in range(10):
nested()
print count
当我调用这个嵌套函数的时候,我希望它能打印出10,但实际上却出现了一个叫做UnboundLocalError的错误。使用global这个关键词可能可以解决这个问题。但是因为这个变量count只在嵌套函数的范围内使用,我不想把它声明为全局变量。那有什么好的方法可以做到这一点呢?
3 个回答
0
对我来说,最优雅的方法是:在两个版本的Python上都能100%运行。
def ex8():
ex8.var = 'foo'
def inner():
ex8.var = 'bar'
print 'inside inner, ex8.var is ', ex8.var
inner()
print 'inside outer function, ex8.var is ', ex8.var
ex8()
inside inner, ex8.var is bar
inside outer function, ex8.var is bar
更多信息请查看:http://www.saltycrane.com/blog/2008/01/python-variable-scope-notes/
5
稍微晚了一点,你可以像这样给“嵌套”函数添加一个属性:
def nesting():
def nested():
nested.count += 1
nested.count = 0
for i in range(10):
nested()
return nested
c = nesting()
print(c.count)
24
在Python 3.x中,你可以使用nonlocal
这个声明(在nested
里面)来告诉Python,你是想给nesting
里的count
变量赋值。
而在Python 2.x中,你不能直接在nested
里给count
赋值。不过,你可以通过不直接给这个变量赋值,而是使用一个可变的容器来解决这个问题:
def nesting():
count = [0]
def nested():
count[0] += 1
for i in range(10):
nested()
print count[0]
不过对于比较复杂的情况,通常的Python做法是把数据和功能放在一个类里,而不是使用闭包。