作用域
python中可以引入作用域的有 函数 类 模块,而 if else try for 等不会引入作用域
LEGB
L local 局部作用域 更改变量需要先声明 global
E enclosing 父级函数的作用域 更改变量需要先声明 nonlocal
G global 全局变量
B built-in 系统变量,例如x = int(10.9), int变量是系统内部封装的一个变量
搜索变量的顺序是:LEGB,先搜所局部变量
a = 5
def func()
a = 4 #这样没法修改这个全局变量
需要这样
global a
a = 4
1 def outer(): 2 count = 10 3 def inner(): 4 count = 15 5 def min(): 6 nonlocal count 7 print(count) 8 count = 100 9 print(count) 10 min() 11 inner() 12 outer()

浙公网安备 33010602011771号