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