Home  >  Article  >  Backend Development  >  Definition and use of global space and local space in Python

Definition and use of global space and local space in Python

王林
王林forward
2023-05-07 16:55:081233browse

    1. Space and local space

    1. Namespace

    The concept of namespace is proposed to divide and control whether variables Visible, as well as the length of the life cycle; the scope of the namespace is called scope.
    Divide an area to save all data and store it in a dictionary (variables and values ​​form a mapping relationship). There are three types in total.

    Built-in namespace:
    Created when the interpreter starts, until the end of the interpreter run, the longest life cycle;
    Global namespace:
    The file is created when it is running, and it will last until the end of the interpreter. The life cycle is long;
    Local namespace:
    The local variables inside are not created until the number is called, and they will be created after the call is completed. Release, shorter life cycle;
    Creation and destruction sequence
    Creation sequence:
    Python interpreter startup->Create built-in namespace->Create global namespace-> ;Create local namespace
    Destruction sequence:
    After the function call is completed->Destroy the local namespace data corresponding to the function->Destroy the global namespace data->Destroy the built-in name Spatial data

    2. Global variables and local variables

    What are global and local variables:

    Local variables are variables defined inside the function. Local variables are located in the local namespace, and their scope is only visible inside the function, which means they can only be used inside the function.

    # 在函数中创建的变量就是局部变量
    def func():
       var = '局部变量'
    
    # 局部变量不可以在非对应局部环境中使用
    print(var)  # error, 该变量不存在

    Global variables are variables defined outside the function or defined inside the function using global. The namespace where the global variable is located is the global namespace. The scope spans the entire file, that is, in the entire file Global variables can be used anywhere.

    # 在全局环境中创建的变量就是全局变量
    var = '全局变量'
    
    def func():
        # 在局部中也可以使用全局变量
        print(var)  # 全局变量
    
    func()

    It is best not to use local variables with the same name as global variables. If they have the same name, the global variable cannot be used in the local environment.

    var = '全局变量'
    
    def func():
        # 先使用了全局变量
        print(var)  # error, 找不到该变量
            # 然后局部变量和全局变量同名,那么新的局部变量就会在局部空间中覆盖了全局变量的一切影响力,这就叫做局部变量修改了全局变量;
        # 这样的话导致在局部空间中无法在使用该全局变量,之前在局部空间中使用的该变量就成为了先调用后定义;导致出错。
        var = '局部变量'
        print(var)
    
    func()
    
    # 但是局部同名变量不会影响到全局变量的值
    print(var)  # 全局变量

    Built-in functions are built-in namespaces, which refer to those built-in functions that come with python.

    3. Scope

    Local variable scope: Inside the function
    Global variable scope:Across the entire file

    4. Life cycle

    Built-in variables-> Global variables-> Local variables
    Built-in variables start when the python program is running and will not be released until the python program ends;
    Global variables are created from the time they are created and will not be released until the program ends or is cleared;
    Local variables are created from the time they are created and will be released until the local space execution ends or is cleared;

    5. All Use of local functions and keywords

    Function

    Definition and use of global space and local space in Python

    ##globals()

    Returns all content in the global scope.

    If it is global, after calling
    globals, all the variables before printing will be obtained, returning the dictionary, global space scope;

    # 定义一些全局变量
    a, b, c = 1, 2, 3
    
    # 调用globals函数
    res = globals()
    
    # 第一次打印,包含a b c
    print(res)
    '''
    结果:
    {&#39;__name__&#39;: &#39;__main__&#39;, &#39;__doc__&#39;: None, &#39;__package__&#39;: None, &#39;__loader__&#39;: <_frozen_importlib_external.SourceFileLoader object at 0x000002DBDCA5D198>, &#39;__spec__&#39;: None, &#39;__annotations__&#39;: {}, &#39;__builtins__&#39;: <module &#39;builtins&#39; (built-in)>, &#39;__file__&#39;: &#39;E:/0-project/python/mymsr/ceshi/test6.py&#39;, &#39;__cached__&#39;: None, &#39;a&#39;: 1, &#39;b&#39;: 2, &#39;c&#39;: 3, &#39;res&#39;: {...}}
    &#39;&#39;&#39;
    
    
    # 再定义一些变量
    d, e, f = 1, 2, 3
    
    # 第二次打印,包含a b c d e f
    print(res)
    &#39;&#39;&#39;
    结果:
    {&#39;__name__&#39;: &#39;__main__&#39;, &#39;__doc__&#39;: None, &#39;__package__&#39;: None, &#39;__loader__&#39;: <_frozen_importlib_external.SourceFileLoader object at 0x000002DBDCA5D198>, &#39;__spec__&#39;: None, &#39;__annotations__&#39;: {}, &#39;__builtins__&#39;: <module &#39;builtins&#39; (built-in)>, &#39;__file__&#39;: &#39;E:/0-project/python/mymsr/ceshi/test6.py&#39;, &#39;__cached__&#39;: None, &#39;a&#39;: 1, &#39;b&#39;: 2, &#39;c&#39;: 3, &#39;res&#39;: {...}, &#39;d&#39;: 1, &#39;e&#39;: 2, &#39;f&#39;: 3}
    &#39;&#39;&#39;

    If it is local, calling

    globals After that, the variables used before the call are obtained, and the dictionary is returned and the global space scope is returned;

    # 定义一些全局变量
    a, b, c = 1, 2, 3
    
    
    # 在局部环境中使用globals函数
    def func():
        res = globals()
        print(res)
    
    
    # 调用函数
    func()
    &#39;&#39;&#39;
    结果:不包含 d e f
    {&#39;__name__&#39;: &#39;__main__&#39;, &#39;__doc__&#39;: None, &#39;__package__&#39;: None, &#39;__loader__&#39;: <_frozen_importlib_external.SourceFileLoader object at 0x000001E7C287D198>, &#39;__spec__&#39;: None, &#39;__annotations__&#39;: {}, &#39;__builtins__&#39;: <module &#39;builtins&#39; (built-in)>, &#39;__file__&#39;: &#39;E:/0-project/python/mymsr/ceshi/test6.py&#39;, &#39;__cached__&#39;: None, &#39;a&#39;: 1, &#39;b&#39;: 2, &#39;c&#39;: 3, &#39;func&#39;: <function func at 0x000001E7C2772F28>}
    &#39;&#39;&#39;
    
    
    # 再定义一些全局变量
    d, e, f = 4, 5, 6
    
    # 第二次调用函数
    func()
    &#39;&#39;&#39;
    结果:包含 d e f
    {&#39;__name__&#39;: &#39;__main__&#39;, &#39;__doc__&#39;: None, &#39;__package__&#39;: None, &#39;__loader__&#39;: <_frozen_importlib_external.SourceFileLoader object at 0x0000021A3F3DD198>, &#39;__spec__&#39;: None, &#39;__annotations__&#39;: {}, &#39;__builtins__&#39;: <module &#39;builtins&#39; (built-in)>, &#39;__file__&#39;: &#39;E:/0-project/python/mymsr/ceshi/test6.py&#39;, &#39;__cached__&#39;: None, &#39;a&#39;: 1, &#39;b&#39;: 2, &#39;c&#39;: 3, &#39;func&#39;: <function func at 0x0000021A3F2D2F28>, &#39;d&#39;: 4, &#39;e&#39;: 5, &#39;f&#39;: 6}
    &#39;&#39;&#39;

    globals can dynamically create global variables

    dic = globals()
    
    print(dic)  # 返回系统的字典
    &#39;&#39;&#39;
    结果:
    {&#39;__name__&#39;: &#39;__main__&#39;, &#39;__doc__&#39;: None, &#39;__package__&#39;: None, &#39;__loader__&#39;: <_frozen_importlib_external.SourceFileLoader object at 0x0000026F357ED198>, &#39;__spec__&#39;: None, &#39;__annotations__&#39;: {}, &#39;__builtins__&#39;: <module &#39;builtins&#39; (built-in)>, &#39;__file__&#39;: &#39;E:/0-project/python/mymsr/ceshi/test6.py&#39;, &#39;__cached__&#39;: None, &#39;dic&#39;: {...}}
    &#39;&#39;&#39;
    
    
    # 在全局的字典当中,通过添加键值对,自动创建全局变量,对应的键是变量名,对应的值是变量指向的值
    dic[&#39;msr123123123&#39;] = &#39;123456&#39;
    
    print(msr123123123) # 123456
    
    # 查看全局内容
    print(dic)
    &#39;&#39;&#39;
    结果:
    {&#39;__name__&#39;: &#39;__main__&#39;, &#39;__doc__&#39;: None, &#39;__package__&#39;: None, &#39;__loader__&#39;: <_frozen_importlib_external.SourceFileLoader object at 0x00000161D944D198>, &#39;__spec__&#39;: None, &#39;__annotations__&#39;: {}, &#39;__builtins__&#39;: <module &#39;builtins&#39; (built-in)>, &#39;__file__&#39;: &#39;E:/0-project/python/mymsr/ceshi/test6.py&#39;, &#39;__cached__&#39;: None, &#39;dic&#39;: {...}, &#39;msr123123123&#39;: &#39;123456&#39;}
    &#39;&#39;&#39;

    locals()

    Return all contents of the current scope.

    If it is global, after calling locals, all variables before printing will be obtained, and the dictionary will be returned to the global space scope;

    # 定义一些全局变量
    a, b, c = 1, 2, 3
    
    # 调用locals函数
    res = locals()
    
    # 第一次打印,包含a b c
    print(res)
    &#39;&#39;&#39;
    结果:
    {&#39;__name__&#39;: &#39;__main__&#39;, &#39;__doc__&#39;: None, &#39;__package__&#39;: None, &#39;__loader__&#39;: <_frozen_importlib_external.SourceFileLoader object at 0x0000018C82A3D198>, &#39;__spec__&#39;: None, &#39;__annotations__&#39;: {}, &#39;__builtins__&#39;: <module &#39;builtins&#39; (built-in)>, &#39;__file__&#39;: &#39;E:/0-project/python/mymsr/ceshi/test1.py&#39;, &#39;__cached__&#39;: None, &#39;a&#39;: 1, &#39;b&#39;: 2, &#39;c&#39;: 3, &#39;res&#39;: {...}}
    &#39;&#39;&#39;
    
    
    # 再定义一些变量
    d, e, f = 1, 2, 3
    
    # 第二次打印,包含a b c d e f
    print(res)
    &#39;&#39;&#39;
    结果:
    {&#39;__name__&#39;: &#39;__main__&#39;, &#39;__doc__&#39;: None, &#39;__package__&#39;: None, &#39;__loader__&#39;: <_frozen_importlib_external.SourceFileLoader object at 0x0000018C82A3D198>, &#39;__spec__&#39;: None, &#39;__annotations__&#39;: {}, &#39;__builtins__&#39;: <module &#39;builtins&#39; (built-in)>, &#39;__file__&#39;: &#39;E:/0-project/python/mymsr/ceshi/test1.py&#39;, &#39;__cached__&#39;: None, &#39;a&#39;: 1, &#39;b&#39;: 2, &#39;c&#39;: 3, &#39;res&#39;: {...}, &#39;d&#39;: 1, &#39;e&#39;: 2, &#39;f&#39;: 3}
    &#39;&#39;&#39;

    If it is local, after calling

    locals, it will be obtained are all variables before the call, return dictionary, local space scope;

    # 定义一些局部变量
    def func():
       # 局部变量
       aa, bb, cc = 11, 22, 33
    
       # 第一遍调用
       res = locals()
    
       # 第一次打印,包含 aa bb cc
       print(res)  # {&#39;cc&#39;: 33, &#39;bb&#39;: 22, &#39;aa&#39;: 11}
    
       # 再定义一些局部变量
       dd, ee, ff = 44, 55, 66
    
       # 第二次打印,不包含 dd ee ff
       print(res)  # {&#39;cc&#39;: 33, &#39;bb&#39;: 22, &#39;aa&#39;: 11}
    
       # 调用第二遍
       res2 = locals()
    
       # 打印第一次的调用,包含 dd ee ff
       print(res)  # {&#39;cc&#39;: 33, &#39;bb&#39;: 22, &#39;aa&#39;: 11, &#39;ff&#39;: 66, &#39;ee&#39;: 55, &#39;dd&#39;: 44, &#39;res&#39;: {...}}
       
       # 打印第二次的调用,包含 dd ee ff
       print(res2) # {&#39;cc&#39;: 33, &#39;bb&#39;: 22, &#39;aa&#39;: 11, &#39;ff&#39;: 66, &#39;ee&#39;: 55, &#39;dd&#39;: 44, &#39;res&#39;: {...}}
    
    # 调用函数,返回在函数中的局部变量
    func()

    Keywords

    Definition and use of global space and local space in Python

    ##global

    Variables created in the local environment are local variables and cannot be used in the global environment. But a variable defined using global is a global variable, which can be used in the global environment.

    def func():
        var = &#39;局部变量&#39;
    
        global glvar
        glvar = &#39;全局变量&#39;
    
    # 一定要执行局部环境哟
    func()
    
    # 全局环境中
    print(var)  # error,局部变量不能调用
    # 使用global定义的变量是全局变量
    print(glvar)    # 全局变量

    The value of global variables cannot be modified in the local environment. Use

    global

    to modify global variables in the local environment. <pre class="brush:py;">var = &amp;#39;全局变量&amp;#39; def func(): global var var = &amp;#39;局部环境中修改&amp;#39; func() print(var) # 局部环境中修改</pre>6. Nesting of functions

    Before learning nonlocal, we need to learn some knowledge about function nesting.

    Inner functions and outer functions

    Functions can be nested in each other. The outer ones are called outer functions, and the inner ones are called inner functions.

    def outer():
        print(&#39;我叫outer,是外函数&#39;)
    
        def inner():
            print(&#39;我叫inner,在outer的里面,是内函数&#39;)
    
        # 在外函数中执行内函数
        inner()
    
    
    # 执行外函数
    outer()
    
    &#39;&#39;&#39;
    结果:
    我叫outer,是外函数
    我叫inner,在outer的里面,是内函数
    &#39;&#39;&#39;

      The inner function cannot be called directly outside the outer function
    • After calling the outer function, the inner function cannot be called outside the function
    • Inner functions can only be called inside the outer function
    • When the inner function is called inside the outer function, there is a sequence and must be defined first before calling. Because Python does not have a pre-reading mechanism, this pre-reading mechanism applies to all scenarios in Python.
    # 外层是outer,内层是inner,最里层是smaller,调用smaller里的所有代码
    def outer():
        print(&#39;我叫outer,是最外层函数,是inner和smaller的外函数&#39;)
    
        def inner():
            print(&#39;我叫inner,是outer的内函数,是smaller的外函数&#39;)
    
            def smaller():
                print(&#39;我叫smaller,是outer和inner的内函数&#39;)
    
            # 先在inner中执行smaller
            smaller()
    
        # 然后在outer中执行inner
        inner()
    
    # 最后再执行outer才能执行smaller函数
    outer()
    
    &#39;&#39;&#39;
    结果:
    我叫outer,是最外层函数,是inner和smaller的外函数
    我叫inner,是outer的内函数,是smaller的外函数
    我叫smaller,是outer和inner的内函数
    &#39;&#39;&#39;

    我们在多个函数嵌套的时候要注意,不管外函数还是内函数,都是函数,只要是函数中的变量都是局部变量。
    内涵可以使用外函数的局部变量,外函数不能直接使用内函数的局部变量。

    二、LEGB原则

    LEGB原则就是一个就近找变量原则,依据就近原则,从下往上,从里向外,依次寻找。

    B————Builtin(Python):Python内置模块的命名空间    (内建作用域)
    G————Global(module):函数外部所在的命名空间        (全局作用域)
    E————Enclosing Function Locals:外部嵌套函数的作用域(嵌套作用域)
    L————Local(Function):当前函数内的作用域           (局部作用域)

    Definition and use of global space and local space in Python

    nonlocal

    现在我们正式学习nonlocal关键字,nonlocal的作用是修改当前局部环境中上一层的局部变量。那么我们根据这个作用便知道了nonlocal的使用环境至少是一个二级的嵌套环境,且外层的局部环境中必须存在一个局部变量。

    def outer():
        # 定义变量
        lvar = &#39;outer var&#39;
    
        def inner():
            # 内函数使用nonlocal修改上一层的局部变量
            nonlocal lvar
            lvar = &#39;inner var&#39;
    
        # 执行inner函数
        inner()
        print(lvar)
    
    outer() # inner var

    假如上一层的局部环境中没有这个变量怎么办,那么就根据LEGB原则向上寻找。

    def outer():
        # 定义变量
        lvar = &#39;outer var&#39;
    
        def inner():
            
            def smaller():
                
                # smaller中修改变量,但是inner中没有,就向上寻找修改outer中的变量
                nonlocal lvar
                lvar = &#39;smaller var&#39;
    
            # 执行 smaller函数
            smaller()
    
        # 执行inner函数
        inner()
        print(lvar)
    
    # 执行outer函数
    outer()

    如果层层寻找,直到最外层的函数中也没有这个变量,那么就会报错,因为nonlocal只会修改局部变量,如果超出范围,就会报错。

    var = 1  # 变量在最外层的函数之外,也就是全局变量,nonlocal无法修改
    
    def outer():
    
       def inner():
    
          def smaller():
    
             nonlocal var    # error,没有局部变量
             var = 2
             print(var)
    
          smaller()
    
       inner()
    
    outer()

    三、总结

    全局变量和局部变量

    局部环境中可以调用全局变量,但是不能修改(但是如果全局变量是可变数据则可以修改其中的值)
    全局环境中不能调用局部变量 也不能修改

    函数
    global()
    (在函数内部使用,可以对全局变量进行操作)

    • 1、可以在局部环境中定义全局变量

    • 2、可以在局部环境中修改全局变量

    nonlocal()
    (在内函数中使用,可以在内函数中修改外函数中的局部变量)

    关键字:

    locals
    1、locals获取当前作用域当中所有的变量
    如果在全局调用locals之后,获取的是打印之前的所有变量,返回字典,全局作用域
    如果在局部调用loclas之后,获取的是调用之前的所有变量,返回字典,局部作用域

    globals
    2、globals只获取全局空间中的所有变量
    如果在全局调用globals之后,获取的是打印之前的所用变量,返回字典,全局作用域
    如果在局部调用globals之后,获取的是调用之前的所用变量,返回字典,全局作用域

    The above is the detailed content of Definition and use of global space and local space in Python. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete