defmy_decorator(func): defwrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper
greet = my_decorator(greet) greet()
输出结果为:
1 2 3
Something is happening before the function is called. Hello, world! Something is happening after the function is called.
使用 @语法糖
为了让代码更加简洁,Python 提供了 @语法糖,用于应用装饰器。上面的例子可以改写为:
1 2 3 4 5 6 7 8 9 10 11 12
defmy_decorator(func): defwrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper
@my_decorator defgreet(): print("Hello, world!")
greet()
这种写法更加直观和易读。
实际应用场景
装饰器在实际开发中有很多应用场景,下面我将介绍几个常见的例子。
1. 记录函数执行时间
在性能优化中,我们常常需要记录函数的执行时间。我们可以编写一个装饰器来实现这一功能:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
import time
deftimer(func): defwrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() print(f"Function {func.__name__} took {end_time - start_time:.4f} seconds to execute.") return result return wrapper
@timer defexample_function(n): total = 0 for i inrange(n): total += i return total
example_function(1000000)
2. 参数检查
在某些情况下,我们需要对函数的参数进行检查,可以通过装饰器来实现:
1 2 3 4 5 6 7 8 9 10 11 12 13
defvalidate_args(func): defwrapper(x, y): ifnotisinstance(x, int) ornotisinstance(y, int): raise ValueError("Both arguments must be integers") return func(x, y) return wrapper