• python3 变量作用域


    1、变量作用域

      Python 中,程序的变量并不是在哪个位置都可以访问的,访问权限决定于这个变量是在哪里赋值的。

      变量的作用域决定了在哪一部分程序可以访问哪个特定的变量名称。Python的作用域一共有4种,分别是:

    • L (Local) 局部作用域
    • E (Enclosing) 闭包函数外的函数中
    • G (Global) 全局作用域
    • B (Built-in) 内置作用域(内置函数所在模块的范围)

      以 L –> E –> G –>B 的规则查找,即:在局部找不到,便会去局部外的局部找(例如闭包),再找不到就会去全局找,再者去内置中找。

    g_count = 0  # 全局作用域
    def outer():
        o_count = 1  # 闭包函数外的函数中
        def inner():
            i_count = 2  # 局部作用域

      Python 中只有模块(module),类(class)以及函数(def、lambda)才会引入新的作用域,其它的代码块(如 if/elif/else/、try/except、for/while等)是不会引入新的作用域的,也就是说这些语句内定义的变量,外部也可以访问,如下代码:

    if True:
    msg = 'I am from China'
    
    print(msg)
    --------------------------------------
    'I am from China'

      实例中 msg 变量定义在 if 语句块中,但外部还是可以访问的。

      如果将 msg 定义在函数中,则它就是局部变量,外部不能访问:

    def test():
            msg_inner = 'I am from China'
    
    print(msg_inner)
    ----------------------------------------------------------
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'msg_inner' is not defined    

      从报错的信息上看,说明了 msg_inner 未定义,无法使用,因为它是局部变量,只有在函数内可以使用。

    2、全局变量和局部变量

      定义在函数内部的变量拥有一个局部作用域,定义在函数外的拥有全局作用域。

      局部变量只能在其被声明的函数内部访问,而全局变量可以在整个程序范围内访问。调用函数时,所有在函数内声明的变量名称都将被加入到作用域中。如下实例:

    total = 0 # 这是一个全局变量
    def sum( arg1, arg2 ):
        #返回2个参数的和."
        total = arg1 + arg2 # total在这里是局部变量.
        print ("函数内是局部变量 : ", total)
        return total
     
    #调用sum函数
    sum( 10, 20 )
    print ("函数外是全局变量 : ", total)
    --------------------------------------------------------
    函数内是局部变量 :  30
    函数外是全局变量 :  0

    3、global 和 nonlocal关键字

      当内部作用域想修改外部作用域的变量时,就要用到global和nonlocal关键字了。

      以下实例修改全局变量 num:

    num = 1
    def fun1():
        global num  # 需要使用 global 关键字声明
        print(num) 
        num = 123
        print(num)
    fun1()
    print(num)
    ---------------------------------------------------------
    1
    123
    123

      如果要修改嵌套作用域(enclosing 作用域,外层非全局作用域)中的变量则需要 nonlocal 关键字了,如下实例:

    def outer():
        num = 10
        def inner():
            nonlocal num   # nonlocal关键字声明
            num = 100
            print(num)
        inner()
        print(num)
    outer()
    ---------------------------------------------------
    100
    100

      还有一种特殊的情况

    a = 10
    def test():
        a = a + 1
        print(a)
    test()        #报错
    ------------------------------
    Traceback (most recent call last):
      File "test.py", line 7, in <module>
        test()
      File "test.py", line 5, in test
        a = a + 1
    UnboundLocalError: local variable 'a' referenced before assignment 

      错误信息为局部作用域引用错误,因为 test 函数中的 a 使用的是局部,未定义,无法修改。

      修改 a 为全局变量,通过函数参数传递,可以正常执行输出结果为:

    a = 10
    def test(a):
        a = a + 1
        print(a)
    test(a)       #报错
    ----------------------------
    11
  • 相关阅读:
    SQL_50题
    Java多线程之冰山一角
    概览
    Selector
    集群配置
    redis config
    分布式、集群
    redis相关技术总结
    redis scan扫描
    redis 单线程 多路io复用
  • 原文地址:https://www.cnblogs.com/490144243msq/p/11019257.html
Copyright © 2020-2023  润新知