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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值