从python内部函数修改函数变量 [英] Modify the function variables from inner function in python
本文介绍了从python内部函数修改函数变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
获取并打印外层函数变量a
It's ok to get and print the outer function variable a
def outer():
a = 1
def inner():
print a
获取外层函数数组a
并追加一些东西也可以
It's also ok to get the outer function array a
and append something
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)?
推荐答案
Python 2 的解决方法:
Workaround for Python 2:
def outer():
a = [1]
def inner():
a[0] += 1
print a[0]
这篇关于从python内部函数修改函数变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文