访问封闭范围中定义的变量

访问封闭范围中定义的变量,第1张

访问封闭范围中定义的变量

在第一种情况下,您指的是可以的

nonlocal
变量,因为没有名为的局部变量
a

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

在第二种情况下,您将创建一个

a
也很好的局部变量(local
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

在第三种情况下,您创建了一个局部变量,但是

print(a+2)
在此之前,这就是引发异常的原因。因为
print(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 atoplevel()

为了实现所需的

nonlocal a
功能,您需要在内部函数中使用:

def toplevel():    a = 5    def nested():        nonlocal a        print(a + 2)        a = 7    nested()    return a


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5601916.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存