参考博客
使用示例
1、基本装饰器
def simple_decorator(func):
def wrapper():
print("Before the function is called.")
func()
print("After the function is called.")
return wrapper
@simple_decorator
def say_hello():
print("Hello, World!")
say_hello()
Before the function is called.
Hello, World!
After the function is called.
@simple_decorator
等价于 say_hello = simple_decorator(say_hello)
,wrapper
在调用 func
的前后增加了额外的功能
2、带参数的装饰器
def decorator_with_args(func):
def wrapper(name):
print(f"Before calling {func.__name__}")
func(name)
print(f"After calling {func.__name__}")
return wrapper
@decorator_with_args
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
Before calling greet
Hello, Alice!
After calling greet
wrapper
接收了 greet
的参数 name
,并在调用 greet
前后添加了额外的逻辑
3、通用装饰器
def universal_decorator(func):
def wrapper(*args, **kwargs):
print(f"Function {func.__name__} is called with arguments {args} and {kwargs}")
result = func(*args, **kwargs)
print(f"Function {func.__name__} returned {result}")
return result
return wrapper
@universal_decorator
def add(a, b):
return a + b
print(add(3, 5))
Function add is called with arguments (3, 5) and {}
Function add returned 8
8
wrapper
捕获了所有参数,并在调用 add
前后打印信息
4、带参数的装饰器
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(times):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def say_hello():
print("Hello!")
say_hello()
Hello!
Hello!
Hello!
@repeat(3)
等价于 say_hello = repeat(3)(say_hello)
repeat
接收参数 times
,控制函数的执行次数
5、类方法装饰器
def method_decorator(func):
def wrapper(self, *args, **kwargs):
print(f"Calling method {func.__name__} of {self}")
return func(self, *args, **kwargs)
return wrapper
class Greeter:
@method_decorator
def greet(self, name):
print(f"Hello, {name}!")
g = Greeter()
g.greet("Alice")
Calling method greet of <__main__.Greeter object at 0x...>
Hello, Alice!
6、装饰器链
def decorator_one(func):
def wrapper(*args, **kwargs):
print("Decorator One")
return func(*args, **kwargs)
return wrapper
def decorator_two(func):
def wrapper(*args, **kwargs):
print("Decorator Two")
return func(*args, **kwargs)
return wrapper
@decorator_one
@decorator_two
def say_hello():
print("Hello!")
say_hello()
Decorator One
Decorator Two
Hello!
7、实际应用
import time
def timer(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:.4f} seconds")
return result
return wrapper
@timer
def slow_function():
time.sleep(2)
print("Finished!")
slow_function()
Finished!
Function slow_function took 2.0001 seconds
装饰器常用于:
- 代码复用 :为多个函数添加相同的功能。
- 日志记录 :记录函数的调用信息。
- 性能监控 :统计函数的执行时间。
- 权限控制 :检查用户权限。
- 缓存 :存储函数的计算结果。