首页 > 编程语言 > 详细

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

时间:2019-10-14 12:29:16      阅读:228      评论:0      收藏:0      [点我收藏+]

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

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

原文:https://www.cnblogs.com/yeni/p/11670057.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!