1. 闭包的定义
闭包是一个函数对象,它可以访问其所在作用域之外的变量。具体来说,闭包是由函数及其相关的引用环境组合而成的实体。
2、闭包的特点:
- 必须有一个内嵌函数(函数中定义的函数)
- 内嵌函数必须引用外部函数中的变量
- 外部函数必须返回内嵌函数
def outer_function(x):# 外部函数的变量y = 10def inner_function():# 内部函数可以访问外部函数的变量return x + yreturn inner_function# 创建闭包
closure = outer_function(5)
# 调用闭包
result = closure() # 结果为15
3、nonlocal关键字
nonlocal的作用
nonlocal用于在内部函数中修改外部函数的变量。它告诉Python这个变量不是局部变量,也不是全局变量,而是外部嵌套函数的变量。
#nonlocal 关键字
# 使用nonlocal关键字来修改外部函数的变量
def counter():count = 0def increment():nonlocal count # 声明count是外部函数的变量count += 1 # 修改外部函数的变量return countreturn increment# 使用闭包
c = counter()
print(c()) # 输出: 1
print(c()) # 输出: 2
print(c()) # 输出: 3
不使用nonlocal关键字报错如下:
# 不使用nonlocal关键字
def counter_without_nonlocal():count = 0def increment():# 如果不使用nonlocalcount = count + 1 # 这会报错!return countreturn increment# 这会引发UnboundLocalError错误
c = counter_without_nonlocal()
print(c()) # 输出: 1
print(c()) # 输出: 2
print(c()) # 输出: 3
4. nonlocal vs global
global_var = 0def outer():outer_var = 1def inner():global global_var # 修改全局变量nonlocal outer_var # 修改外部函数的变量global_var += 1outer_var += 1print(global_var,outer_var)return innero=outer()
o()
o()
o()打印结果
1 2
2 3
3 4