一、什么是闭包?先用一句人话解释
闭包 = 函数 + 它创建时所捕获的外部变量
也可以理解为:
'带私有状态的函数'
二、一个最小但完整的闭包示例
def make_adder(x):
():
x + y
adder
Python 闭包概念,即函数捕获外部变量形成带状态的对象。通过对比普通函数与类,展示闭包在轻量级对象构建中的优势。结合 Callable 类型注解,阐述了闭包在 Agent、回调及配置型函数等工程场景中的应用,并给出了适用与不适用闭包的判断标准。
闭包 = 函数 + 它创建时所捕获的外部变量
也可以理解为:
'带私有状态的函数'
def make_adder(x):
():
x + y
adder
使用方式:
add_10 = make_adder(10)
print(add_10(5)) # 15
print(add_10(20)) # 30
make_adder(10) 执行完后,本应销毁adder记住了 x = 10x 被'封'在函数里 —— 这就是 closure📌 重点:
x 并不是参数,而是被'捕获'的变量
def add(x, y):
return x + y
def make_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
使用:
c = make_counter()
print(c()) # 1
print(c()) # 2
print(c()) # 3
👉 你得到了一个不依赖 class 的'对象'
我们用 class 对比一下:
class Counter:
def __init__(self):
self.count = 0
def next(self):
self.count += 1
return self.count
而闭包版本:
def make_counter():
count = 0
def next():
nonlocal count
count += 1
return count
return next
| 对比项 | 闭包 | class |
|---|---|---|
| 语法复杂度 | 低 | 高 |
| 私有状态 | 天然支持 | 需要 self |
| 适合 Agent / 回调 | ✅ | 一般 |
| 适合复杂模型 | 一般 | ✅ |
📌 这也是为什么 AI / LangChain 场景大量用闭包
def make_logger(prefix):
def log(message):
print(f"[{prefix}] {message}")
return log
使用:
info = make_logger("INFO")
error = make_logger("ERROR")
info("service started")
error("db connection failed")
👉 不需要 class
👉 不需要全局变量
👉 每个 logger 都是'定制实例'
from typing import Callable
def build_agent() -> Callable[[str], str]:
memory = []
def agent(prompt: str) -> str:
memory.append(prompt)
return f"History size: {len(memory)}"
return agent
使用:
agent = build_agent()
print(agent("hi")) # History size: 1
print(agent("hello")) # History size: 2
🧠 这里的 agent 就是一个'带状态的函数对象'
先看这行代码:
def build_agent() -> Callable[[str], str]:
build_agent返回一个函数
这个函数:接收str返回str
等价于 Java:
Function<String,String>
def build_agent():
...
def build_agent() -> Callable[[str], str]:
你立刻知道:
📌 Callable = 闭包的'类型说明书'
def require_role(role):
def check(user_role):
return user_role == role
return check
def lazy_sum(*nums):
def calc():
return sum(nums)
return calc
def make_strategy(rate):
def apply(price):
return price * rate
return apply
👉 那种场景用 class
闭包让函数拥有'状态',Callable 让函数拥有'类型'
在现代 Python(尤其是 AI / Web / 工程领域):
闭包 + Callable = 轻量级对象系统

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online