
点击上面“蓝字”关注我们

变量作用域层次
L(local)局部作用域
E(Enclosed)嵌套(闭包)作用域
G(Global)全局作用域
B(Built-in)内置作用域
作用域使用规则
作用域内变量可直接读取, 修改, 删除
上层变量无法读取下层变量, 下层变量可读取上层变量, 但只可读取, 如果需要修改, 则需要关键字声明
从上往下顺序创建,从下往上搜索,即搜索遵循L –> E–> G –> B原则,如果都搜索不到则会抛出NameError报错。
作用域
L(local)局部作用域
作用域范围
只在当前代码块或者当前函数中有效
注意: 当在外部调用时, 会抛出 NameError
1 2 3 4 5 6 7 8 9 10
| def local(): total = 1 # 局部变量 print("local fuction", total) # 输出 # local fuction 1
local() # 在函数外部调用, 报错 # NameError: name 'total' is not defined print(total)
|
E(Enclosed)嵌套作用域
作用域范围
整个闭包函数(outer)内有效, 但是嵌套函数(inner)内定义的变量, 在闭包(outer)内会报错
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| def outer(): out_total = 1 # 闭包(嵌套作用域) def inner(): in_total = 2 print("inner in_total", in_total) # inner in_total 2 print("inner out_total", out_total) # inner out_total 1 print("outer out_total", out_total) # outer out_total 1 # 如果print, 会报错 # print("outer in_total", in_total) # NameError: name 'in_total' is not defined return inner()
outer()
|
G(Global)全局作用域
作用域范围
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| 在整个模块中都可以用 注意: 在函数内部只可以读取, 修改删除需要global声明
total = 1 # 全局变量
def local(): print("local fuction", total) # 输出 # local fuction 1
local() # 输出 # global 1 print("global", total)
作用域范围: 在整个程序都有效, 如__name__, __builtin__
print("__doc__", __doc__) # __doc__ None print("__name__", __name__) # __name__ __main__
|
global
声明变量是全局变量
格式:
1 2 3
| def 函数名(): global 变量名 函数功能代码...
|
示例:
使用局部变量报错的例子
1 2 3 4 5 6 7 8 9 10 11 12 13
| total = 1 # 全局变量
def local(): global total print("local fuction", total) # 输出 # local fuction 1 total = 2
local() # 输出 # global 2 print("global", total)
|
nonlocal
声明变量是闭包变量
格式:
1 2 3
| def 函数名(): nonlocal 变量名 函数功能代码...
|
举例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| out_total = 0 def outer(): out_total = 1 def nonlocal_inner(): nonlocal out_total # 修改的是闭包变量out_total print("raw nonlocal out_total", out_total) out_total = 2 print("Update nonlocal out_total", out_total)
def global_inner(): global out_total # 修改的是全局变量的ut_total print("raw global out_total", out_total) out_total = 3 print("Update global out_total", out_total)
nonlocal_inner() global_inner() # 闭包变量修改为2 print("nonlocal out_total", out_total)
outer() # 全局变量修改为3 print("global out_total", out_total)
# 输出 # raw nonlocal out_total 1 # Update nonlocal out_total 2 # raw global out_total 0 # Update global out_total 3 # nonlocal out_total 2 # global out_total 3
|
好看的人才能点
