栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/596580.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号