获取并打印外层函数变量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 2 的解决方法:
def outer():
a = [1]
def inner():
a[0] += 1
print a[0]
关于python - 从python内部函数修改函数变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13985671/