python中的作用域
python中的作用域分4种情况:
- L:local,局部作用域,即函数中定义的变量;
- E:enclosing,嵌套的父级函数的局部作用域,即包含此函数的上级函数的局部作用域,但不是全局的;
- G:globa,全局变量,就是模块级别定义的变量;
- B:built-in,系统固定模块里面的变量,比如int, bytearray等。 搜索变量的优先级顺序依次是:作用域局部>外层作用域>当前模块中的全局>python内置作用域,也就是LEGB。
1 2 3 4 5 6 7 8 9 10 11 12 13 | x = int ( 2.9 ) # int built-in g_count = 0 # global def outer(): o_count = 1 # enclosing def inner(): i_count = 2 # local print (o_count) # print(i_count) 找不到 inner() outer() # print(o_count) #找不到 |
当然,local和enclosing是相对的,enclosing变量相对上层来说也是local。
5.2 作用域产生
在Python中,只有模块(module),类(class)以及函数(def、lambda)才会引入新的作用域,其它的代码块(如if、try、for等)是不会引入新的作用域的,如下代码:
1 2 3 | if 2 > 1 : x = 1 print (x) # 1 |
这个是没有问题的,if并没有引入一个新的作用域,x仍处在当前作用域中,后面代码可以使用。
1 2 3 | def test(): x = 2 print (x) # NameError: name 'x2' is not defined |
def、class、lambda是可以引入新作用域的。
5.3 变量的修改
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | ################# x = 6 def f2(): print (x) x = 5 f2() # 错误的原因在于print(x)时,解释器会在局部作用域找,会找到x=5(函数已经加载到内存),但x使用在声明前了,所以报错: # local variable 'x' referenced before assignment.如何证明找到了x=5呢?简单:注释掉x=5,x=6 # 报错为:name 'x' is not defined #同理 x = 6 def f2(): x + = 1 #local variable 'x' referenced before assignment. f2() |
5.4 global关键字
当内部作用域想修改外部作用域的变量时,就要用到global和nonlocal关键字了,当修改的变量是在全局作用域(global作用域)上的,就要使用global先声明一下,代码如下:
1 2 3 4 5 6 7 8 9 | count = 10 def outer(): global count print (count) count = 100 print (count) outer() #10 #100 |
5.5 nonlocal关键字
global关键字声明的变量必须在全局作用域上,不能嵌套作用域上,当要修改嵌套作用域(enclosing作用域,外层非全局作用域)中的变量怎么办呢,这时就需要nonlocal关键字了
1 2 3 4 5 6 7 8 9 10 11 | def outer(): count = 10 def inner(): nonlocal count count = 20 print (count) inner() print (count) outer() #20 #20 |
5.6 小结
(1)变量查找顺序:LEGB,作用域局部>外层作用域>当前模块中的全局>python内置作用域;
(2)只有模块、类、及函数才能引入新作用域;
(3)对于一个变量,内部作用域先声明就会覆盖外部变量,不声明直接使用,就会使用外部作用域的变量;
(4)内部作用域要修改外部作用域变量的值时,全局变量要使用global关键字,嵌套作用域变量要使用nonlocal关键字。nonlocal是python3新增的关键字,有了这个 关键字,就能完美的实现闭包了。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步