• python中的作用域


    python中的作用域分4种情况:

    • L:local,局部作用域,即函数中定义的变量;
    • E:enclosing,嵌套的父级函数的局部作用域,即包含此函数的上级函数的局部作用域,但不是全局的;
    • G:globa,全局变量,就是模块级别定义的变量;
    • B:built-in,系统固定模块里面的变量,比如int, bytearray等。 搜索变量的优先级顺序依次是:作用域局部>外层作用域>当前模块中的全局>python内置作用域,也就是LEGB。
    x = int(2.9)  # int built-in
     
    g_count = 0  # global
    def outer():
        o_count = 1  # enclosing
        def inner():
            i_count = 2  # local
            print(o_count)
        # print(i_count) 找不到
        inner() 
    outer()
     
    # print(o_count) #找不到
    

      

    当然,local和enclosing是相对的,enclosing变量相对上层来说也是local。

    5.2 作用域产生 

    在Python中,只有模块(module),类(class)以及函数(def、lambda)才会引入新的作用域,其它的代码块(如if、try、for等)是不会引入新的作用域的,如下代码:

    if 2>1:
        x = 1
    print(x)  # 1
    

      

    这个是没有问题的,if并没有引入一个新的作用域,x仍处在当前作用域中,后面代码可以使用。

    def test():
        x = 2
    print(x) # NameError: name 'x2' is not defined
    

      

    def、class、lambda是可以引入新作用域的。 

    5.3 变量的修改 

    #################
    x=6
    def f2():
        print(x)
        x=5
    f2()
      
    # 错误的原因在于print(x)时,解释器会在局部作用域找,会找到x=5(函数已经加载到内存),但x使用在声明前了,所以报错:
    # local variable 'x' referenced before assignment.如何证明找到了x=5呢?简单:注释掉x=5,x=6
    # 报错为:name 'x' is not defined
    #同理
    x=6
    def f2():
        x+=1 #local variable 'x' referenced before assignment.
    f2()

    5.4 global关键字 

    当内部作用域想修改外部作用域的变量时,就要用到global和nonlocal关键字了,当修改的变量是在全局作用域(global作用域)上的,就要使用global先声明一下,代码如下:

    count = 10
    def outer():
        global count
        print(count) 
        count = 100
        print(count)
    outer()
    #10
    #100

    5.5 nonlocal关键字 

    global关键字声明的变量必须在全局作用域上,不能嵌套作用域上,当要修改嵌套作用域(enclosing作用域,外层非全局作用域)中的变量怎么办呢,这时就需要nonlocal关键字了

    def outer():
        count = 10
        def inner():
            nonlocal count
            count = 20
            print(count)
        inner()
        print(count)
    outer()
    #20
    #20 

    5.6 小结 

    (1)变量查找顺序:LEGB,作用域局部>外层作用域>当前模块中的全局>python内置作用域;

    (2)只有模块、类、及函数才能引入新作用域;

    (3)对于一个变量,内部作用域先声明就会覆盖外部变量,不声明直接使用,就会使用外部作用域的变量;

    (4)内部作用域要修改外部作用域变量的值时,全局变量要使用global关键字,嵌套作用域变量要使用nonlocal关键字。nonlocal是python3新增的关键字,有了这个 关键字,就能完美的实现闭包了。 

  • 相关阅读:
    JavaScript WebSocket C# SuperSocket.WebSocket 示例
    Nginx 配置
    Temporary Post Used For Theme Detection (272f6d70fb8946f3a568afd3d7b053bd 3bfe001a32de4114a6b44005b770f6d7)
    SpringBoot多数据源事务解决方案
    SpringBoot集成mybatis拦截器修改表名
    点击各个按钮,在执行操作之前出现确认提示框
    incoming change和current change
    Expected Number with value 8, got String with value "8".
    正则只能输入数字遇到的问题
    Antd 4.19 Modal + Form;打开modal时使用setFieldsValue,首次回显正常,第二次无效?
  • 原文地址:https://www.cnblogs.com/wjcoding/p/11011859.html
Copyright © 2020-2023  润新知