1. 原理
L:local,局部作用域,即函数中定义的变量;
E:enclosing,嵌套的父级函数的局部作用域,即包含此函数的上级函数的局部作用域,但不是全局的;
G:global,全局变量,就是模块级别定义的变量;
B:built-in,系统固定模块里面的变量,比如int, bytearray等。
搜索变量的优先级顺序依次是:局部作用域>外层作用域>当前模块中的全局>python内置作用域,也就是LEGB。
x = int(10) #python内置作用域B
y = 2 #当前模块中的全局变量G
def outfuction():
outfx = 2 #外层作用域E
def infunction():
infx = 3 #局部作用域L
2. 作用域产生的场景
-
会引入新的作用域:module,class,def
-
不会引入新的作用域:if,for,try--except
-
注意:如果在外部引用局部变量,本质已经变成“在外部定义或者引用了一个新的全局变量”,如:
x = 123 #全局G
def test_1():
x = 345 #局部变量x是L,屏蔽了作为G的x
print(x) #345test_1() #345
print(x, ' ') #123,这里的x是Gdef test_2():
y = 456 #局部变量y
print(y)test_2() #456
y = 'haozhang' #等价于创造了新的全局变量y
print(y) #haozhang
test_2() #456
在函数内部却要访问全局变量:用global
x = 1
def outfx():
global x #global改变了G区变量
print(x) #1
x = 2
outfx()
print(x) #2
内部函数访问嵌套的父函数的变量:用nonlocal
def outfx():
x = 1
def infx():
nonlocal x #nonlocal改变了E区变量
x = 2
print(x) #2
infx()
print(x) #2
outfx()