Python 装饰器完全指南
深入理解 Python 装饰器,学习如何编写优雅的装饰器。
Python 装饰器完全指南
装饰器是 Python 中强大的语法糖。
什么是装饰器?
装饰器是一个函数,它接受另一个函数并扩展其行为。
def simple_decorator(func): def wrapper(): print("Before function call") func() print("After function call") return wrapper
@simple_decoratordef say_hello(): print("Hello!")
say_hello()带参数的装饰器
def repeat(times): def decorator(func): def wrapper(*args, **kwargs): for _ in range(times): result = func(*args, **kwargs) return result return wrapper return decorator
@repeat(times=3)def greet(name): print(f"Hello, {name}!")
greet("World")保留函数元信息
import functools
def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper类装饰器
class CountCalls: def __init__(self, func): functools.update_wrapper(self, func) self.func = func self.count = 0
def __call__(self, *args, **kwargs): self.count += 1 print(f"Call {self.count} of {self.func.__name__}") return self.func(*args, **kwargs)
@CountCallsdef fibonacci(n): if n < 2: return n return fibonacci(n - 1) + fibonacci(n - 2)实际应用:性能监控
import time
def timer(func): @functools.wraps(func) def wrapper(*args, **kwargs): start = time.perf_counter() result = func(*args, **kwargs) end = time.perf_counter() print(f"{func.__name__} 执行时间: {end - start:.4f} 秒") return result return wrapper
@timerdef expensive_operation(): time.sleep(1) return "Done"装饰器让代码更优雅!