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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM