• PythonNote040---命名空间globals、locals、vars


      基础概念问题,举几个例子,尝试理解~

    命名空间

    A namespace is a mapping from names to objects.Most namespaces are currently implemented as Python dictionaries。
    命名空间(Namespace)是从名称到对象的映射,大部分的命名空间都是通过 Python 字典来实现的。
    命名空间也称作用域,三种命名空间:

    • 内置名称(built-in names), Python 语言内置的名称,比如函数名 abs、char 和异常名称 BaseException、Exception 等等
    • 全局名称(global names),模块中定义的名称,记录了模块的变量,包括函数、类、其它导入的模块、模块级的变量和常量
    • 局部名称(local names),函数中定义的名称,记录了函数的变量,包括函数的参数和局部定义的变量。(类中定义的也是)

    当我们使用变量顺序时,查找顺序为:局部的命名空间 -> 全局命名空间 -> 内置命名空间
    具体到函数中,首先查找函数内部定义的变量,其次全局,最后内置命名空间
    如果找不到,则抛NameError异常

    main_y = 'main'
    main_z = 'main'    
    def test():
        test_x = 1
        main_y = 'test'
        print(f"test_x = {test_x}")
        print(f"main_y = {main_y}")
        var_name = "main_y"
        print(f'locals() {var_name}:{locals().get(var_name, None)}')
        print(f'globals() {var_name}:{globals().get(var_name, None)}')
        print(f"main_z = {main_z}")
        var_name = "main_z"
        print(f'locals() {var_name}:{locals().get(var_name, None)}')
        print(f'globals() {var_name}:{globals().get(var_name, None)}')
    
    test()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    test_x = 1
    main_y = test
    locals() main_y:test
    globals() main_y:main
    main_z = main
    locals() main_z:None
    globals() main_z:main
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • main_y变量函数内部定义,即局部命名空间有,直接获取
    • main_z在全局命名空间内获取

    作用域

    感觉可以粗略当做命名空间,贴下官方定义:
    A scope is a textual region of a Python program where a namespace is directly accessible. “Directly accessible” here means that an unqualified reference to a name attempts to find the name in the namespace.
    作用域就是一个 Python 程序可以直接访问命名空间的正文区域。

    在一个 python 程序中,直接访问一个变量,会从内到外依次访问所有的作用域直到找到,否则会报未定义的错误。

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

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

    有四种作用域:

    • L(Local):最内层,包含局部变量,比如一个函数/方法内部
    • E(Enclosing):包含了非局部(non-local)也非全局(non-global)的变量。比如两个嵌套函数,一个函数(或类) A 里面又包含了一个函数 B ,那么对于 B 中的名称来说 A 中的作用域就为 nonlocal
    • G(Global):当前脚本的最外层,比如当前模块的全局变量
    • B(Built-in): 包含了内建的变量/关键字等,最后被搜索
      规则顺序: L –> E –> G –> B
      在局部找不到,便会去局部外的局部找(例如闭包),再找不到就会去全局找,再者去内置中找

    全局变量和局部变量

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

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

    这个也不多说,看看定义即可
    如果内部作用域想修改外部作用域变量,咋整?

    num = 1
    def fun1():
        global num  # 需要使用 global 关键字声明
        print(num) 
        num = 123
        print(num)
    fun1()
    print(num)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    1
    123
    123
    
    • 1
    • 2
    • 3

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

    def outer():
        num = 10
        def inner():
            nonlocal num   # nonlocal关键字声明
            num = 100
            print(num)
        inner()
        print(num)
    outer()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    100
    100
    
    • 1
    • 2

    globals、locals、vars

    class A(object):
        def __init__(self, db, table):
            self.db = db
            self.table = table
    
    • 1
    • 2
    • 3
    • 4
    vars(A)
    
    • 1
    mappingproxy({'__module__': '__main__',
                  '__init__': ,
                  '__dict__': ,
                  '__weakref__': ,
                  '__doc__': None})
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • locals() 实际上没有返回局部名字空间,它返回的是一个拷贝。所以对它进行修改,修改的是拷贝,而对实际的局部名字空间中的变量值并无影响
    • globals() 返回的是实际的全局名字空间
    • vars()没有参数时等价于locals,有参数时等价于object.__dict__

    • globals() always returns the dictionary of the module namespace
    • locals() always returns a dictionary of the current namespace
    • vars() returns either a dictionary of the current namespace (if called with no argument) or the dictionary of the argument
     def test():
        test_x = 1
        var_name = "test_x"
        print(f'locals() {var_name}:{locals().get(var_name, None)}')
        print(f"main_z = {main_z}")
        locals()['a'] = 3
        var_name = "a"
        print(f'locals() {var_name}:{locals().get(var_name, None)}')
        print(f'vars() {var_name}:{vars().get(var_name, None)}')
        # print(f'a={a}')
        print(id(a))
    
    test()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    locals() test_x:1
    main_z = main
    locals() a:3
    vars() a:3
    
    
    
    ---------------------------------------------------------------------------
    
    NameError                                 Traceback (most recent call last)
    
    ~\AppData\Local\Temp\ipykernel_24820\2806725260.py in 
         11    print(id(a))
         12 
    ---> 13 test()
    
    
    ~\AppData\Local\Temp\ipykernel_24820\2806725260.py in test()
          9    print(f'vars() {var_name}:{vars().get(var_name, None)}')
         10    # print(f'a={a}')
    ---> 11    print(id(a))
         12 
         13 test()
    
    
    NameError: name 'a' is not defined
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    虽然修改了locals中的值,但是后续的变量引用仍然失败,即局部空间不存在该变量

    乱七八糟的稍微整理下,原理还是不清晰,先这样吧~

    Ref

    [1] https://www.runoob.com/python3/python3-namespace-scope.html
    [2] https://stackoverflow.com/questions/7969949/whats-the-difference-between-globals-locals-and-vars

    
    
    • 1
  • 相关阅读:
    “简单”的无限魔方
    Servlet上传文件
    百度抓取香港服务器抓取超时是什么情况?
    借鉴前端事件机制的Spring AOP
    采购数智化爆发在即,支出宝“3+2“体系助力企业打造核心竞争优势
    PHP 反射
    LeetCode199. Binary Tree Right Side View
    如何使用iPhone15在办公室观看家里电脑上的4k电影,实现公网访问本地群晖!
    Matlab实验二
    Hadoop使用hdfs指令查看hdfs目录的根目录显示被拒
  • 原文地址:https://blog.csdn.net/wendaomudong_l2d4/article/details/128062233