情況一: 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