rsk*_*rsk 2 python variables scope
我有以下代码:
>>> def f(v=1):
... def ff():
... print v
... v = 2
... ff()
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in f
File "<stdin>", line 3, in ff
UnboundLocalError: local variable 'v' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
我确实理解为什么会出现这个消息(Python变量范围问题),但v在这种情况下如何使用变量呢?global v在这种情况下不起作用.
在Python 3.x中,您可以使用nonlocal:
def f(v=1):
def ff():
nonlocal v
print(v)
v = 2
ff()
Run Code Online (Sandbox Code Playgroud)
在Python 2.x中,没有简单的解决方案.黑客就是v列出一个清单:
def f(v=None):
if v is None:
v = [1]
def ff():
print v[0]
v[0] = 2
ff()
Run Code Online (Sandbox Code Playgroud)