bxx*_*bxx 16 python global-variables nested-function
我想在嵌套函数中定义变量,以便在嵌套函数中进行更改,例如
def nesting():
count = 0
def nested():
count += 1
for i in range(10):
nested()
print count
Run Code Online (Sandbox Code Playgroud)
当调用嵌套函数时,我希望它打印10,但它会引发UnboundLocalError.全球关键词可以解决这个问题.但由于变量计数仅用于嵌套函数的范围,我希望不要将其声明为全局变量.这样做的好方法是什么?
Tho*_*ers 21
在Python 3.x中,您可以使用nonlocal
声明(in nested
)告诉Python您要分配给count
变量nesting
.
在Python 2.x中,你根本无法分配给count
在nesting
从nested
.但是,您可以通过不分配给变量本身,但使用可变容器来解决它:
def nesting():
count = [0]
def nested():
count[0] += 1
for i in range(10):
nested()
print count[0]
Run Code Online (Sandbox Code Playgroud)
虽然对于非平凡的情况,通常的Python方法是将数据和功能包装在一个类中,而不是使用闭包.
小智 5
有点晚了,您可以将属性附加到"嵌套"函数,如下所示:
def nesting():
def nested():
nested.count += 1
nested.count = 0
for i in range(10):
nested()
return nested
c = nesting()
print(c.count)
Run Code Online (Sandbox Code Playgroud)