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
    
    
相关推荐
飞奔的瓜牛6 小时前
Ansible 实战:典型使用场景、Playbook 编写与 Python 调用接口详解
python·servlet·ansible
萧子琦8 小时前
不装 C++ Snappy 也能秒解 LevelDB .ldb?拿 3 套公开取证靶场对拍 StarShield v0.4.1、dfindexeddb 与 strings
python
JonaHu9 小时前
GPT Image 2.6 商品图横竖版适配:安全区、留白与裁切预检
图像处理·人工智能·python·aigc
Fancy.7619 小时前
Python变量与基础数据类型学习总结
python
泡海椒10 小时前
Java 生成资金流向图 PDF:jquick-pdf 树图(JTreeChartData)节点尺寸与间距的追问记录
java·python·pdf
钱栈up11 小时前
奥迪上汽拍板「三年三款」,合资阵营的换挡节奏终于跟上了
爬虫·python·数据分析
东莞市云毅网络有限公司11 小时前
SQLite FTS5 做中文问答检索:分词、排序与召回测试
python·sqlite·自动化运维·geo·数据监测
timeDifference₇21 小时前
Python Vibe Coding实操实验报告
开发语言·jvm·python
geovindu1 天前
python:DecisionTree
开发语言·后端·python·算法
怒放的生命19911 天前
代码知识库 RAG 问答系统 —— 从 0 到 1 实现教程
python·状态模式·fastapi·全栈开发·ai agent应用开发