栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【Python】1.nonlocal 关键字、测试LEGB

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

【Python】1.nonlocal 关键字、测试LEGB

#nonlocal 用来声明外层的局部变量。 #global 用来声明全局变量。
#测试nonlocal,global关键字的用法
a = 100

def outer():
    b = 10

    def inner():
        nonlocal b       #声明外部函数的局部变量
        print("inner:",b)
        b = 20
    inner()
    print("outer:",b)
    global a            #声明全局变量
    a = 1000
    print("inner:",a)


outer()
结果:nonlocal改变的外部函数outer中b的值。
inner: 10
outer: 20
inner: 1000

Process finished with exit code 0
#测试LEGB Python 在查找“名称”时,是按照 LEGB 规则查找的: Local-->Enclosed-->Global-->Built in Local         指的就是函数或者类的方法内部 Enclosed        指的是嵌套函数(一个函数包裹另一个函数,闭包) Global         指的是模块中的全局变量 Built in        指的是 Python为自己保留的特殊名称。
# str = "global str"
def outer():
    # str = "outer"
    def inner():
        str = "inner"    #定义在函数内部的str
        print(str)

    inner()

outer()

输出: inner

str = "global str"
def outer():
   #  str = "outer"
    def inner():
       # str = "inner"
        print(str)

    inner()

outer()

输出:global str

# str = "global str"
def outer():
    # str = "outer"
    def inner():
       # str = "inner"
        print(str)

    inner()

outer()

分析:现在函数内部、嵌套函数内及全局变量中均不含str,则找python自身的保留字str

输出:



Process finished with exit code 0

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

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

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