鉴于:
def f():
x = 0
def g():
h()
def h():
x += 1
print(x)
g()
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in f
File "<stdin>", line 4, in g
File "<stdin>", line 6, in h
UnboundLocalError: local variable 'x' referenced before assignment
>>>
Run Code Online (Sandbox Code Playgroud)
如何h查看x变量?
谢谢.
编辑
本来应该提到的,我使用的是Python 2.7.3
ovg*_*vin 12
你可以创建x一个函数属性:
def f():
f.x = 0
def g():
h()
def h():
f.x += 1
print(f.x)
g()
Run Code Online (Sandbox Code Playgroud)
此外,从Python 3开始,您可以使用nonlocal关键字.
小智 5
如果您使用的是Python 3,则使用nonlocal关键字.放在nonlocal x功能的开头h.如果您使用的是Python 2.x,则解决方法是创建x一个包含一个元素的列表,以便您可以对其进行修改:
def f():
x = [0]
def g():
h()
def h():
x[0] += 1
print x[0]
g()
f()
Run Code Online (Sandbox Code Playgroud)
在Python 3中只需使用nonlocal:
def f():
x = 0
def g():
h()
def h():
nonlocal x
x += 1
print(x)
g()
f()
Run Code Online (Sandbox Code Playgroud)