[英]Modify the function variables from inner function in python
It's ok to get and print the outer function variable a
可以获取并打印外部函数变量
a
def outer():
a = 1
def inner():
print a
It's also ok to get the outer function array a
and append something 也可以获取外部函数数组
a
并附加一些内容
def outer():
a = []
def inner():
a.append(1)
print a
However, it caused some trouble when I tried to increase the integer: 但是,当我尝试增加整数时,这引起了一些麻烦:
def outer():
a = 1
def inner():
a += 1 #or a = a + 1
print a
>> UnboundLocalError: local variable 'a' referenced before assignment
Why does this happen and how can I achieve my goal (increase the integer)? 为什么会发生这种情况,如何实现我的目标(增加整数)?
In Python 3 you can do this with the nonlocal
keyword. 在Python 3中,您可以使用
nonlocal
关键字执行此操作。 Do nonlocal a
at the beginning of inner
to mark a
as nonlocal. 在
inner
的开头执行nonlocal a
,以将a
标记为非本地。
In Python 2 it is not possible. 在Python 2中是不可能的。
A generally cleaner way to do this would be: 通常更干净的方法是:
def outer():
a = 1
def inner(b):
b += 1
return b
a = inner(a)
Python allows a lot, but non-local variables can be generally considered as "dirty" (without going into details here). Python允许很多,但是非局部变量通常可以被认为是“脏的”(这里不做详细介绍)。
Workaround for Python 2: Python 2的解决方法:
def outer():
a = [1]
def inner():
a[0] += 1
print a[0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.