Python 闭包实现的计数器,每调用一次就 +1,多个计数器之间互不干扰

Python 闭包实现的计数器,每调用一次就 +1,多个计数器之间互不干扰

flyfish

cpp 复制代码
How Closures are Created
A closure is formed when:

	A function is defined inside another function (nested function).
	The inner function references variables from the outer function.
	The outer function returns the inner function.
cpp 复制代码
闭包是如何形成的
三个形成条件
	一个函数定义在另一个函数内部(这就是嵌套函数)。
	内部函数引用了外部函数的变量(自由变量)。
	外部函数将内部函数返回。

举例

cpp 复制代码
def say():
    greeting = 'Hello'

    def display():
        print(greeting)

    display()

闭包就是其中的

cpp 复制代码
greeting = 'Hello'

def display():
    print(greeting)

实现计数器,每调用一次就 +1,多个计数器之间互不干扰

实现方式1

nonlocal = 非局部

在嵌套 / 内部函数中,声明要修改的变量来 自外层函数 ,既不是当前函数的局部变量,也不是全局变量。

python 复制代码
def create_counter():
    # 自由变量:只属于当前闭包的状态
    count = 0

    # 嵌套内部函数
    def add():
        # 引用外部作用域的变量 count
        nonlocal count
        count += 1
        return count

    # 外部函数返回内部函数
    return add


# 创建两个独立的计数器
counter1 = create_counter()
counter2 = create_counter()

# 各自计数,互不干扰
print(counter1())  # 1
print(counter1())  # 2
print(counter1())  # 3

print(counter2())  # 1
print(counter2())  # 2

实现方式2

python 复制代码
def create_counter():
    # 用可变对象列表存储计数(绕过lambda不能赋值/nonlocal的限制)
    count = [0]
    # 返回 lambda 匿名函数(闭包:引用外部自由变量 count)
    return lambda: (count.__setitem__(0, count[0] + 1), count[0])[1]

# 创建两个独立计数器
counter1 = create_counter()
counter2 = create_counter()

# 执行结果和原版完全一致!
print(counter1())  # 1
print(counter1())  # 2
print(counter1())  # 3

print(counter2())  # 1
print(counter2())  # 2

实现方式3

python 复制代码
def create_counter():
    count = [0]
    return lambda: (count.__setitem__(0, count[0] + 1), count[0])[1]

# 创建两个独立计数器
counter1 = create_counter()
counter2 = create_counter()

# 执行结果和原版完全一致!
print(counter1())  # 1
print(counter1())  # 2
print(counter1())  # 3

print(counter2())  # 1
print(counter2())  # 2
    
    
相关推荐
默_笙5 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
qq_426003965 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫5 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技5 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读5 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时5 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
奇思妙想聪明勤奋的小羊5 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1235 天前
2026年第38周GitHub趋势周报
python·科技·github
IZero075 天前
Jev 与 Laya
python·语言模型