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
    
    
相关推荐
把我格子衫拿来35 分钟前
VTK 体绘制入门到排错:传递函数、采样距离与透明度的关系
python·vtk·可视化·医学影像·体绘制
张张123y6 小时前
后端第一课:输入 URL 后发生了什么?我用手写 Socket 把全链路跑通了
python·websocket·ai·socket·url·后端开发
全栈弄潮儿8 小时前
Python实战第7期:字典与集合
后端·python·编程语言
2603_965148118 小时前
电商选品调研:通过关键词搜索API获取市场热销商品,结合商品详情API分析竞品卖点与定价
开发语言·数据库·人工智能·python·信息可视化
xixiaoyunya9 小时前
Python 异步编程入门:用 asyncio 轻松实现并发任务
开发语言·python·php
把我格子衫拿来9 小时前
Dice 很高就够了吗?分割评价中的 IoU、表面距离与 HD95
python·图像分割·模型评估·医学影像·dice
曲径海盗9 小时前
【Python 学习第 31 天】复习:变量与数据类型 等 3 题
python·学习笔记·编程入门
Data_Journal10 小时前
如何绕过 Cloudflare:网页抓取的最佳方法
网络·python
我命由我1234510 小时前
智能助手通用问答边界
人工智能·python·学习·ai·学习方法·ai编程·智能体
Angeldream12311 小时前
第 4 章 医学影像预处理
图像处理·人工智能·python·医学影像·医学影像处理