Home > Article > Backend Development > Definition and use of global space and local space in Python
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
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.
Local variable scope: Inside the function
Global variable scope:Across the entire file
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;
Function
##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) ''' 结果: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000002DBDCA5D198>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:/0-project/python/mymsr/ceshi/test6.py', '__cached__': None, 'a': 1, 'b': 2, 'c': 3, 'res': {...}} ''' # 再定义一些变量 d, e, f = 1, 2, 3 # 第二次打印,包含a b c d e f print(res) ''' 结果: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000002DBDCA5D198>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:/0-project/python/mymsr/ceshi/test6.py', '__cached__': None, 'a': 1, 'b': 2, 'c': 3, 'res': {...}, 'd': 1, 'e': 2, 'f': 3} '''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() ''' 结果:不包含 d e f {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001E7C287D198>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:/0-project/python/mymsr/ceshi/test6.py', '__cached__': None, 'a': 1, 'b': 2, 'c': 3, 'func': <function func at 0x000001E7C2772F28>} ''' # 再定义一些全局变量 d, e, f = 4, 5, 6 # 第二次调用函数 func() ''' 结果:包含 d e f {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000021A3F3DD198>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:/0-project/python/mymsr/ceshi/test6.py', '__cached__': None, 'a': 1, 'b': 2, 'c': 3, 'func': <function func at 0x0000021A3F2D2F28>, 'd': 4, 'e': 5, 'f': 6} '''globals can dynamically create global variables
dic = globals() print(dic) # 返回系统的字典 ''' 结果: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000026F357ED198>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:/0-project/python/mymsr/ceshi/test6.py', '__cached__': None, 'dic': {...}} ''' # 在全局的字典当中,通过添加键值对,自动创建全局变量,对应的键是变量名,对应的值是变量指向的值 dic['msr123123123'] = '123456' print(msr123123123) # 123456 # 查看全局内容 print(dic) ''' 结果: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000161D944D198>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:/0-project/python/mymsr/ceshi/test6.py', '__cached__': None, 'dic': {...}, 'msr123123123': '123456'} '''
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) ''' 结果: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000018C82A3D198>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:/0-project/python/mymsr/ceshi/test1.py', '__cached__': None, 'a': 1, 'b': 2, 'c': 3, 'res': {...}} ''' # 再定义一些变量 d, e, f = 1, 2, 3 # 第二次打印,包含a b c d e f print(res) ''' 结果: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000018C82A3D198>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:/0-project/python/mymsr/ceshi/test1.py', '__cached__': None, 'a': 1, 'b': 2, 'c': 3, 'res': {...}, 'd': 1, 'e': 2, 'f': 3} '''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) # {'cc': 33, 'bb': 22, 'aa': 11} # 再定义一些局部变量 dd, ee, ff = 44, 55, 66 # 第二次打印,不包含 dd ee ff print(res) # {'cc': 33, 'bb': 22, 'aa': 11} # 调用第二遍 res2 = locals() # 打印第一次的调用,包含 dd ee ff print(res) # {'cc': 33, 'bb': 22, 'aa': 11, 'ff': 66, 'ee': 55, 'dd': 44, 'res': {...}} # 打印第二次的调用,包含 dd ee ff print(res2) # {'cc': 33, 'bb': 22, 'aa': 11, 'ff': 66, 'ee': 55, 'dd': 44, 'res': {...}} # 调用函数,返回在函数中的局部变量 func()
Keywords
##globalVariables 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 = '局部变量' global glvar glvar = '全局变量' # 一定要执行局部环境哟 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 = &#39;全局变量&#39;
def func():
global var
var = &#39;局部环境中修改&#39;
func()
print(var) # 局部环境中修改</pre>
6. Nesting of 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('我叫outer,是外函数') def inner(): print('我叫inner,在outer的里面,是内函数') # 在外函数中执行内函数 inner() # 执行外函数 outer() ''' 结果: 我叫outer,是外函数 我叫inner,在outer的里面,是内函数 '''
# 外层是outer,内层是inner,最里层是smaller,调用smaller里的所有代码 def outer(): print('我叫outer,是最外层函数,是inner和smaller的外函数') def inner(): print('我叫inner,是outer的内函数,是smaller的外函数') def smaller(): print('我叫smaller,是outer和inner的内函数') # 先在inner中执行smaller smaller() # 然后在outer中执行inner inner() # 最后再执行outer才能执行smaller函数 outer() ''' 结果: 我叫outer,是最外层函数,是inner和smaller的外函数 我叫inner,是outer的内函数,是smaller的外函数 我叫smaller,是outer和inner的内函数 '''
我们在多个函数嵌套的时候要注意,不管外函数还是内函数,都是函数,只要是函数中的变量都是局部变量。
内涵可以使用外函数的局部变量,外函数不能直接使用内函数的局部变量。
LEGB原则就是一个就近找变量原则,依据就近原则,从下往上,从里向外,依次寻找。
B————Builtin(Python):Python内置模块的命名空间 (内建作用域)
G————Global(module):函数外部所在的命名空间 (全局作用域)
E————Enclosing Function Locals:外部嵌套函数的作用域(嵌套作用域)
L————Local(Function):当前函数内的作用域 (局部作用域)
nonlocal
现在我们正式学习nonlocal关键字,nonlocal的作用是修改当前局部环境中上一层的局部变量。那么我们根据这个作用便知道了nonlocal的使用环境至少是一个二级的嵌套环境,且外层的局部环境中必须存在一个局部变量。
def outer(): # 定义变量 lvar = 'outer var' def inner(): # 内函数使用nonlocal修改上一层的局部变量 nonlocal lvar lvar = 'inner var' # 执行inner函数 inner() print(lvar) outer() # inner var
假如上一层的局部环境中没有这个变量怎么办,那么就根据LEGB原则向上寻找。
def outer(): # 定义变量 lvar = 'outer var' def inner(): def smaller(): # smaller中修改变量,但是inner中没有,就向上寻找修改outer中的变量 nonlocal lvar lvar = 'smaller var' # 执行 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!