Python 装饰器的 10 个应用场景详解
装饰器本质上是一个高阶函数,它接受一个函数作为参数并返回一个新函数。通过使用 @ 符号语法糖,我们可以将装饰器应用于任何函数或类,从而在不修改原函数代码的前提下增强其功能。在实际开发中,合理使用装饰器可以显著提高代码的可读性和可维护性。
在使用自定义装饰器时,建议结合 functools.wraps 来保留原函数的元数据(如名称、文档字符串等),避免调试困难。
基础示例
import functools
def my_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print("Something is happening before the function is called.")
result = func(*args, **kwargs)
print("Something is happening after the function is called.")
return result
return wrapper
@my_decorator
def say_hello():
"""Say hello"""
print("Hello!")
say_hello()
常见应用场景
1. 日志记录
装饰器可以用来记录函数的调用细节,这在调试和监控应用时非常有用。通过记录输入参数和返回值,可以快速定位问题。
import logging
logging.basicConfig(level=logging.INFO)
def log_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
logging.info(f"{func.__name__} was called with args={args}, kwargs={kwargs}")
result = func(*args, **kwargs)
logging.info(f" returned ")
result
wrapper
():
x + y


