python 使用嵌套函数报local variable xxx referenced before assignment或者 local variable XXX defined in enclosing scope

情况一: a 直接引用外部的,正常运行

def toplevel():
a = 5
def nested():
print(a + 2) # theres no local variable a so it prints the nonlocal one
nested()
return a

情况二:创建local 变量a,直接打印,正常运行

def toplevel():
a = 5
def nested():
a = 7 # create a local variable called a which is different than the nonlocal one
print(a) # prints 7
nested()
print(a) # prints 5
return a

情况三:由于存在 a = 7,此时a代表嵌套函数中的local a , 但在使用a + 2 时,a还未有定义出来,所以报错

def toplevel():
a = 5
def nested():
print(a + 2) # tries to print local variable a but its created after this line so exception is raised
a = 7
nested()
return a
toplevel()

针对情况三的解决方法, 在嵌套函数中增加nonlocal a ,代表a专指外部变量即可

def toplevel():
a = 5
def nested():
nonlocal a
print(a + 2)
a = 7
nested()
return a
上一篇:hdu 5147 Sequence II


下一篇:local variable 'xxx' referenced before assignment