Python中的闭包

什么是闭包?

先给一个简单的定义:

闭包是嵌套函数的一种特殊形式,满足两个核心条件:

  1. 内层函数引用了外层函数的变量(而非全局变量);
  2. 外层函数返回了内层函数(而非执行内层函数)。

闭包的核心价值是:保留外层函数的变量环境,即使外层函数执行完毕,内层函数依然能访问到这些变量。

简单示例

python 复制代码
def outer():
    print("这是外部函数")
    username = "zhangsan"   #局部变量
    def inner():
        print("这是内部函数")
        print("username:", username)
    return inner

res = outer()
res()   #inner()

#运行结果
这是外部函数
这是内部函数
username: zhangsan

闭包的核心应用

Python 装饰器本质就是闭包,比如实现一个 "计算函数执行时间" 的装饰器:

python 复制代码
import time

def timer_decorator(func):
    # 外层函数接收被装饰的函数
    def wrapper(*args, **kwargs):
        # 内层函数封装额外逻辑
        start = time.time()
        result = func(*args, **kwargs)  # 执行原函数
        end = time.time()
        print(f"函数 {func.__name__} 执行耗时:{end - start:.4f} 秒")
        return result
    return wrapper

# 使用装饰器
@timer_decorator
def test_func():
    time.sleep(0.5)

test_func()  # 输出:函数 test_func 执行耗时:0.5001 秒
相关推荐
AI探索者11 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者11 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh13 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅13 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽14 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时17 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿20 小时前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780511 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng81 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi2 天前
Chapter 2 - Python中的变量和简单的数据类型
python