一文掌握Python修饰器:直白教程与案例

张开发
2026/4/11 20:55:38 15 分钟阅读

分享文章

一文掌握Python修饰器:直白教程与案例
一、前言刚学 Python 的时候初学者很容易对修饰器存在以下几个疑问xxx到底做了什么为什么函数可以“包函数”闭包到底是个啥这篇文章我用最直白的方式带你彻底搞懂它。二、从一个最简单的需求开始假设我们有一个这样一个函数def say_hello(): print(hello)现在我们需要做一件事在函数执行前后打印日志效果类似before hello after最直觉的写法def say_hello(): print(before) print(hello) print(after)这种做法的问题是当需要修改的函数太多时如果有 100 个函数怎么办全都改一遍这明显不合理三、函数“包函数”的思路python的修饰器就是用来解决这样的问题的。我们可以这样写def wrapper(): print(before) say_hello() print(after)调用wrapper()虽然能实现但问题来了❗ 每个函数都要写一个 wrapper四、关键突破函数可以作为参数Python 中函数是“第一类对象”可以传来传去def decorator(func): def wrapper(): print(before) func() print(after) return wrapper使用def say_hello(): print(hello) say_hello decorator(say_hello) say_hello()输出before hello after五、语法的本质重点上面的写法可以简化成decorator def say_hello(): print(hello)等价于say_hello decorator(say_hello)一句话理解修饰器 用一个新函数替换原函数六、修饰器结构图强烈建议理解原函数 → decorator → wrapper → 执行原函数更直白一点你调用的已经不是原函数了而是 wrapper七、进阶支持参数和返回值如果原函数有参数怎么办def decorator(func): def wrapper(*args, **kwargs): print(before) result func(*args, **kwargs) print(after) return result return wrapper使用decorator def add(a, b): return a b print(add(1, 2))输出before after 3八、实际案例1. 登录验证def login_required(func): def wrapper(*args, **kwargs): print(验证用户是否登录) return func(*args, **kwargs) return wrapperlogin_required def profile(): print(进入个人中心)2. 函数执行时间统计import time def timer(func): def wrapper(*args, **kwargs): start time.time() result func(*args, **kwargs) end time.time() print(f耗时{end - start:.4f}s) return result return wrapper3. 日志记录def log(func): def wrapper(*args, **kwargs): print(f调用函数{func.__name__}) return func(*args, **kwargs) return wrapper九、一个常见的坑你可能会发现print(say_hello.__name__)输出变成wrapper原函数信息丢失了解决方法from functools import wraps def decorator(func): wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper十、终极总结一定要记住修饰器的本质函数作为参数传递闭包函数嵌套函数返回一个新函数一句话总结修饰器 在不修改原函数的情况下增强它的功能写在最后如果你也和我一样一开始看不懂修饰器被 搞得很困惑那记住一件事不要死记概念一定要自己手写一遍当你亲手写出来的时候你就真的懂了。

更多文章