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