• 11 作用域


    1.命名空间

    什么是命名空间

    比如有一个学校,有10个班级,在7班和8班中都有一个叫“小王”的同学,如果在学校的广播中呼叫“小王”时,7班和8班中的这2个人就纳闷了,你是喊谁呢!!!如果是“7班的小王”的话,那么就很明确了,那么此时的7班就是小王所在的范围,即命名空间

    globals、locals

    在之前学习变量的作用域时,经常会提到局部变量和全局变量,之所有称之为局部、全局,就是因为他们的自作用的区域不同,这就是作用域

    >>> globals()
    {'__name__': '__main__', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__builtins__': <module 'builtins' (built-in)>, '__doc__': None, 'a': 100, '__spec__': None, '__package__': None}
    >>> 
    >>> def test():
    ...     a = 100
    ...     b = 200
    ...     print(locals())
    ... 
    >>> test()
    {'b': 200, 'a': 100}
    >>> 

    2.LEGB 规则

    Python 使用 LEGB 的顺序来查找一个符号对应的对象

    locals -> enclosing function -> globals -> builtins
    
    • locals,当前所在命名空间(如函数、模块),函数的参数也属于命名空间内的变量
    • enclosing,外部嵌套函数的命名空间(闭包中常见)
    • globals,全局变量,函数定义所在模块的命名空间
    • builtins,内建模块的命名空间。

     

      1)版本1

     num = 100
     def test():
         num = 200  #当前所在命名空间
         print(num)
     
     test()

      2)版本2:自己有用自己的

    num = 100
    def test():
        num = 200
        def test_in():
            num = 300
            print(num)
        return test_in
    
    ret = test()
    ret()
    
    
    ####
    300

      3)版本3:自己没有到上一层

    num = 100
    def test():
        num = 200  #外部嵌套函数的命名空间(闭包中常见)
        def test_in():
     #       num = 300
            print(num)
        return test_in
    
    ret = test()
    ret()
    
    
    ####
    200

       4)版本4:全局变量

    num = 100     #全局变量,函数定义所在模块的命名空间
    def test():
        # num = 200  
        def test_in():
     #       num = 300
            print(num)
        return test_in
    
    ret = test()
    ret()
    
    
    ####
    100

      5)版本5:内建空间

    python@ubuntu:~/02-就业班/03-高级-$ ipython3
    
    In [2]: dir(__builtin__)
    Out[2]: 
    ['ArithmeticError',
     'AssertionError',
     'AttributeError',
     'BaseException',
     'BlockingIOError',
     'BrokenPipeError',
     'BufferError',
     'memoryview',
     'min',
     'next',
     'object',
     'oct',
     'open',]
  • 相关阅读:
    NFS4.1规范研究:session
    散列冲突与作为特征值的散列
    使用Select的3个注意事项
    3个学习Socket编程的简单例子:TCP Server/Client, Select
    Gdb调试多进程程序
    Usage of pmake
    诡异的bug: tcsh陷入死循环
    【转】PowerDesigner 物理数据模型(PDM) 说明
    大批量文件处理的7条建议
    OLE DB、ODBC 和 Oracle 连接池 (ADO.NET)
  • 原文地址:https://www.cnblogs.com/venicid/p/7940423.html
Copyright © 2020-2023  润新知