zoukankan      html  css  js  c++  java
  • Python 函数的作用域

    python中的作用域有4种:

    名称 介绍
    L local,局部作用域,函数中定义的变量;
    E enclosing,嵌套的父级函数的局部作用域,即包含此函数的上级函数的局部作用域,但不是全局的;
    B globa,全局变量,就是模块级别定义的变量;
    G built-in,系统固定模块里面的变量,比如int, bytearray等。

    搜索变量的优先级顺序依次是(LEGB):
    作用域局部 > 外层作用域 > 当前模块中的全局 > python内置作用域。

    number = 10             # number 是全局变量,作用域在整个程序中
    def test():
        print(number)
        a = 8               # a 是局部变量,作用域在 test 函数内
        print(a)
    
    test()
    
    运行结果:
    10
    8
    
    def outer():
        o_num = 1          # enclosing
        i_num = 2          # enclosing
        def inner():
            i_num = 8      # local
            print(i_num)   # local 变量优先
            print(o_num)
        inner()
    outer()
    
    运行结果:
    8
    1
    
    num = 1
    def add():
        num += 1
        print(num)
    add()
    
    运行结果:
    UnboundLocalError: local variable 'num' referenced before assignment
    

    如果想在函数中修改全局变量,需要在函数内部在变量前加上 global 关键字

    num = 1                    # global 变量
    def add():
        global num             # 加上 global 关键字
        num += 1
        print(num)
    add()
    
    运行结果:
    2
    

    同理,如果希望在内层函数中修改外层的 enclosing 变量,需要加上 nonlocal 关键字

    def outer():
        num = 1                  # enclosing 变量
        def inner():
            nonlocal num         # 加上 nonlocal 关键字
            num = 2
            print(num)
        inner()
        print(num)
    outer()
    
    运行结果:
    2
    2
    

    另外我们需要注意的是:

    1.只有模块、类、及函数才能引入新作用域;
    2.对于一个变量,内部作用域先声明就会覆盖外部变量,不声明直接使用,就会使用外部作用域的变量(这时只能查看,无法修改);
    3.如果内部作用域要修改外部作用域变量的值时, 全局变量要使用 global 关键字,嵌套作用域变量要使用 nonlocal 关键字。

  • 相关阅读:
    __doPostBack的使用
    【转】function,new,constructor and prototye
    谈谈一些网页游戏失败的原因到底有哪些?(转)
    全面剖析页游巨头发家史(转)
    2013.02.20开通博客
    老子喜欢的女人
    如何成为强大的程序员?(转)
    注重健康
    学习方法总结
    数据库知识点滴积累
  • 原文地址:https://www.cnblogs.com/klvchen/p/8724269.html
Copyright © 2011-2022 走看看