python四种作用域、闭包

局部作用域(Local)
定义: 函数的内部就是局部作用域,局部作用域中的变量,只能在该函数内部可见
特点:
- 每次调用函数都会创建一个新的局部作用域
- 函数运行结束后,局部作用域随之销毁
- 局部作用域优先级最高
- 参数也是属于局部作用域的
外层作用域(Enclosing)
定义: 如果函数中又定义了函数,那么外层函数的作用域,就是内层函数的Enclosing作用域
特点:
- 只有当函数“嵌套”时才会出现,
- 内层函数可以读取外层函数变量
- 想修改外层变量必须使用nonlocal
def test1():
a = 100
def test2():
nonlocal a
a = 200
print(f'A的值是{a}')
test2()
# a = 200, 内层函数使用了nonlocal
print(f'外层函数的A值是{a}')
test1()全局作用域(Global)
定义:.py文件就是全局作用域,全局作用域中的变量,在当前.py文件的任何位置都可以访问
特点:
- 全局变量只在当前.py文件中可见
- 函数内部可以使用global关键字修改全局变量
内建/置作用域(Built-in)
定义:python预先定义好的东西,会放在内建作用域中,所有的.py文件都可以直接使用
特点:
- 所有.py文件都能直接使用其中的名称
- 例如:print、len、type、range
- 查找优先级最低
查找顺序
Local -> Endosing -> Global -> Built-in
闭包
定义:内层函数 + 被内层函数所引用的外层变量
闭包产生的条件
- 要有函数嵌套
- 在内层函数中,要访问/操作有外层函数的变量
- 并且外层函数要返回内层函数——只有返回了内层函数,闭包才能活下来
例子
def other():
num = 10
def inner():
print(num)
return inner
f = other()
# 打印 __closure__元组
print(f.__closure__)
# 10, 也就是num的值;__closure__能保存具体值
print(f.__closure__[0].cell_contents)
# 结论
# 1. other 函数中,被inner所使用到的那些变量,会被封存到【闭包单元(cell)】中。
# 2. 这些 cell 会组成一个 __closure__元组,最终放在了inner函数身上
注意点:
- 调用n次外层函数,就会得到n个不同的闭包,并且这些闭包之间互不影响
- 内层函数中用到的外层变量是可变对象,多个闭包之间依然互不影响
# 调用n次外层函数,就会得到n个不同的闭包,并且这些闭包之间互不影响
def other():
num = 10
def inner():
nonlocal num
num += 1
print(num)
return inner
f1 = other()
f2 = other()
f1() # 11
f1() # 12
f1() # 13
f2() # 11
# 内层函数中用到的外层变量是可变对象,多个闭包之间依然互不影响
def other():
nums = []
def inner(val):
nums.append(val)
print(nums)
return inner
f1 = other()
f2 = other()
f1(10) # [10]
f1(20) # [10, 20]
f1(30) # [10, 20, 30]
f2(666) # [666]
