装饰器是python中用于增强函数行为的特殊函数。它接受一个函数作为参数并返回一个新的函数,从而可以在不修改原函数代码的情况下为其添加额外功能。通过@符号应用装饰器,其基本结构依赖于函数嵌套和闭包,使用args和*kwargs以支持任意参数,并可通过functools.wraps保留原函数元数据。常见应用场景包括:1. 记录日志或性能计时;2. 权限检查或登录验证;3. 缓存函数结果以避免重复计算。当多个装饰器同时存在时,执行顺序是从下往上依次包裹并外层先执行。掌握装饰器的关键在于理解函数包装机制、处理带参情况以及正确使用wraps工具。
在 Python 中,装饰器是一个非常实用的功能,它允许我们在不修改函数本身的前提下,为函数添加额外功能。简单来说,装饰器就是一个接收函数作为参数的函数,并返回一个新的函数。
装饰器本质上是一个函数,也可以是一个类,它的作用是包装另一个函数或类,以增强其行为。Python 使用 @ 符号来应用装饰器。
例如:
立即学习“Python免费学习笔记(深入)”;
def my_decorator(func): def wrapper(): print("Before function call") func() print("After function call") return wrapper @my_decorator def say_hello(): print("Hello") say_hello()
运行结果:
Before function call Hello After function call
在这个例子中,my_decorator 是一个装饰器,它“包裹”了 say_hello 函数,让它在执行前后打印了一些信息。
装饰器的核心在于函数嵌套和闭包的使用。基本结构如下:
def decorator(func): def wrapper(*args, **kwargs): # 前置操作 result = func(*args, **kwargs) # 后置操作 return result return wrapper @decorator def some_function(): pass
几点关键说明:
from functools import wraps def decorator(func): @wraps(func) def wrapper(*args, **kwargs): ... return func(*args, **kwargs) return wrapper
装饰器的用途非常广泛,下面是一些常见的使用场景:
你可以用装饰器来记录函数的执行时间或者调用次数,这对调试和性能分析很有帮助。
import time def timer(func): def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) print(f"{func.__name__} took {time.time() - start:.4f}s") return result return wrapper @timer def sleep_seconds(seconds): time.sleep(seconds) sleep_seconds(1)
在 Web 开发中,经常需要用装饰器来做权限校验,比如 Flask 或 Django 中的 @login_required。
def login_required(func): def wrapper(user, *args, **kwargs): if user.is_authenticated: return func(user, *args, **kwargs) else: print("Access denied: User not logged in") return wrapper @login_required def access_profile(user): print(f"Accessing profile for {user.name}")
装饰器可以用来缓存函数的计算结果,避免重复计算。
def memoize(func): cache = {} def wrapper(*args): if args in cache: return cache[args] result = func(*args) cache[args] = result return result return wrapper @memoize def fibonacci(n): if n <= 1: return n return fibonacci(n - 1) + fibonacci(n - 2)
当一个函数被多个装饰器修饰时,它们的执行顺序是从下往上(从内到外)的。例如:
def deco1(func): def wrapper(): print("Start deco1") func() print("End deco1") return wrapper def deco2(func): def wrapper(): print("Start deco2") func() print("End deco2") return wrapper @deco1 @deco2 def say_hi(): print("Hi") say_hi()
输出结果:
Start deco1 Start deco2 Hi End deco2 End deco1
可以看到,deco2 先被应用,但它的执行是在 deco1 包裹之后。
基本上就这些了。装饰器虽然看起来有点绕,但只要理解它是“函数包装”的一种方式,再结合实际场景去练习,就能很快掌握。关键是要会写带参数的装饰器、多个装饰器叠加的情况,以及记得用 functools.wraps 来保留原函数信息。
以上就是Python中如何使用装饰器?语法与应用场景解析的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号