在Python中,装饰器(Decorator)是一种特殊的语法,用于修改函数或类的行为。装饰器本质上是一个函数,它可以接受一个函数或类作为参数,并返回一个新的函数或类,以实现对原始函数或类的增强或修改。装饰器通常用于在不修改原始代码的情况下添加功能或行为
- 常见的用途包括:
- 记录日志:在函数执行前后记录函数的调用和返回结果。
- 计时:在函数执行前后记录函数的执行时间。
- 权限验证:在函数执行前验证用户的权限或登录状态。
- 缓存:将函数的结果缓存起来,避免重复计算。
- 注册插件:在函数执行时执行一系列注册的插件函数。
import time
def timing_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Function {func.__name__} took {end_time - start_time} seconds to execute.")
return result
return wrapper
@timing_decorator
def my_function():
time.sleep(2)
print("Function executed!")
my_function()
输出
Function executed!
Function my_function took 2.0002450942993164 seconds to execute.
通过使用装饰器,我们可以在不修改my_function的情况下,添加了计时功能。装饰器为函数提供了一种简洁和可复用的方式来添加功能。