![](/img/trans.png)
[英]modify variables outside of function scope from within a function in python 3.5
[英]Modify the function variables from inner function in python
可以获取并打印外部函数变量a
def outer():
a = 1
def inner():
print a
也可以获取外部函数数组a
并附加一些内容
def outer():
a = []
def inner():
a.append(1)
print a
但是,当我尝试增加整数时,这引起了一些麻烦:
def outer():
a = 1
def inner():
a += 1 #or a = a + 1
print a
>> UnboundLocalError: local variable 'a' referenced before assignment
为什么会发生这种情况,如何实现我的目标(增加整数)?
在Python 3中,您可以使用nonlocal
关键字执行此操作。 在inner
的开头执行nonlocal a
,以将a
标记为非本地。
在Python 2中是不可能的。
通常更干净的方法是:
def outer():
a = 1
def inner(b):
b += 1
return b
a = inner(a)
Python允许很多,但是非局部变量通常可以被认为是“脏的”(这里不做详细介绍)。
Python 2的解决方法:
def outer():
a = [1]
def inner():
a[0] += 1
print a[0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.