可能是重复的问题:
如何在Python中从内部函数修改函数变量
假设我有下面这段Python代码
def f():
x=2
def y():
x+=3
y()
这引发了以下问题:
UnboundLocalError: local variable 'x' referenced before assignment
那么,我如何从内部函数“修改”局部变量'x'?在内部函数中将x定义为全局变量也会引发错误。
可能是重复的问题:
如何在Python中从内部函数修改函数变量
假设我有下面这段Python代码
def f():
x=2
def y():
x+=3
y()
UnboundLocalError: local variable 'x' referenced before assignment
在Python 3中,您可以使用nonlocal
语句:
>>> def f():
... x = 2
... def y():
... nonlocal x
... x += 3
... print(x)
... y()
... print(x)
...
>>> f()
5
5
在Python 2中,您需要将变量声明为外部函数的属性,以实现相同的功能。>>> def f():
... f.x = 2
... def y():
... f.x += 3
... print(f.x)
... y()
... print(f.x)
...
>>> f()
5
5
或者我们也可以使用 字典
或者 列表
:
>>> def f():
... dct = {'x': 2}
... def y():
... dct['x'] += 3
... print(dct['x'])
... y()
... print(dct['x'])
...
>>> f()
5
5
dict
或list
,但那看起来不太符合Python的风格。 - Ashwini Chaudhary