问题描述
我希望嵌套函数中定义的变量可以在嵌套函数中进行更改,例如
I'd like to have variable defined in the nesting function to be altered in the nested function, something like
def nesting():
count = 0
def nested():
count += 1
for i in range(10):
nested()
print count
当嵌套函数被调用时,我希望打印10,但它引发UnboundLocalError。全球关键词可以解决这个问题。但由于变量计数只用于嵌套函数的范围,因此我不希望将其声明为全局函数。什么是这样做的好方法?
When nesting function is called, I wish it prints 10, but it raises UnboundLocalError. The key word global may resolve this. But as the variable count is only used in the scope of nesting function, I expect not to declare it global. What is the good way to do this?
推荐答案
在Python 3.x中,您可以使用非本地的
声明(在嵌套
中)告诉Python你的意思是分配给 count
变量在嵌套
中。
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
.
在Python 2.x中,您无法将其分配给在
。但是,您可以通过不分配给变量本身,而是使用可变容器来解决它:嵌套
中从嵌套
计数
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]
平凡的情况下,通常的Python方法是将数据和功能包装在一个类中,而不是使用闭包。
Although for non-trivial cases, the usual Python approach is to wrap the data and functionality in a class, rather than using closures.
这篇关于如何在嵌套函数中更改嵌套函数的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!