Python标准库装饰器完全指南
一、内置装饰器
1. @property
作用: 将方法转换为属性访问
适用场景:
- 属性值校验(如年龄不能为负数)
- 延迟计算属性值
- 兼容旧版属性访问API
class BankAccount:
def __init__(self):
self._balance = 0
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, value):
if value < 0:
raise ValueError("余额不能为负")
self._balance = value
account = BankAccount()
account.balance = 100
print(account.balance) # 100
2. @classmethod
作用: 定义类方法
适用场景:
- 创建工厂方法
- 实现单例模式
- 类级别的配置管理
class Logger:
_instance = None
@classmethod
def instance(cls):
if not cls._instance:
cls._instance = cls()
return cls._instance
log1 = Logger.instance()
log2 = Logger.instance()
print(log1 is log2) # True
3. @staticmethod
作用: 定义静态方法
适用场景:
- 工具类函数
- 数学计算辅助方法
- 与类相关但无需访问状态的函数
class MathUtils:
@staticmethod
def clamp(value, min_val, max_val):
return max(min(value, max_val), min_val)
print(MathUtils.clamp(15, 0, 10)) # 10
二、functools模块
4. @lru_cache
作用: 缓存函数计算结果
适用场景:
- 递归函数优化
- API调用结果缓存
- 计算密集型函数优化
from functools import lru_cache
@lru_cache(maxsize=128)
def factorial(n):
return 1 if n == 0 else n * factorial(n-1)
print(factorial(10)) # 3628800
5. @wraps
作用: 保留原函数元信息
适用场景:
- 构建装饰器链
- 维护函数文档
- 调试时保留函数签名
from functools import wraps
def log_args(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(f"参数: {args}")
return func(*args, **kwargs)
return wrapper
@log_args
def add(a, b):
"""两数相加"""
return a + b
print(add.__name__) # add
6. @singledispatch
作用: 实现函数重载
适用场景:
- 处理多类型参数
- 数据序列化
- 多态函数实现
from functools import singledispatch
@singledispatch
def print_type(obj):
print("未知类型")
@print_type.register(int)
def _(obj):
print("整数类型")
print_type(42) # 整数类型
print_type("42") # 未知类型
7. @total_ordering
作用: 自动生成比较方法
适用场景:
- 简化比较运算符实现
- 需要排序的类
- 减少样板代码
from functools import total_ordering
@total_ordering
class Version:
def __init__(self, major, minor):
self.major = major
self.minor = minor
def __eq__(self, other):
return (self.major, self.minor) == (other.major, other.minor)
def __lt__(self, other):
return (self.major, self.minor) < (other.major, other.minor)
v1 = Version(1, 2)
v2 = Version(2, 0)
print(v1 < v2) # True
8. @cached_property (Python 3.8+)
作用: 缓存属性计算结果
适用场景:
- 复杂属性计算
- 数据库连接延迟初始化
- 线程安全属性缓存
from functools import cached_property
class Dataset:
def __init__(self, data):
self.data = data
@cached_property
def stats(self):
print("计算统计数据...")
return {
'mean': sum(self.data)/len(self.data),
'max': max(self.data)
}
ds = Dataset([1,2,3])
print(ds.stats) # 计算统计数据...
print(ds.stats) # 直接返回缓存
三、contextlib模块
9. @contextmanager
作用: 创建上下文管理器
适用场景:
- 资源管理(文件/网络)
- 计时器实现
- 临时环境配置
from contextlib import contextmanager
@contextmanager
def lock_resource(lock):
lock.acquire()
try:
yield
finally:
lock.release()
# 使用示例
lock = threading.Lock()
with lock_resource(lock):
# 执行需要加锁的操作
pass
四、dataclasses模块
10. @dataclass (Python 3.7+)
作用: 自动生成数据类方法
适用场景:
- 数据容器类
- 配置对象
- 简化类定义
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
z: float = 0.0
p = Point(1.5, 2.5)
print(p) # Point(x=1.5, y=2.5, z=0.0)
五、abc模块
11. @abstractmethod
作用: 定义抽象方法
适用场景:
- 定义接口规范
- 框架基类设计
- 强制子类实现特定方法
from abc import ABC, abstractmethod
class Renderer(ABC):
@abstractmethod
def render(self):
pass
class HTMLRenderer(Renderer):
def render(self):
return ""
# Renderer() # 报错
html = HTMLRenderer()
print(html.render())
六、atexit模块
12. @register
作用: 注册退出处理函数
适用场景:
- 资源清理
- 保存程序状态
- 服务关闭处理
import atexit
@atexit.register
def cleanup():
print("执行清理操作...")
print("程序运行中...")
# 退出时输出清理信息
七、unittest模块
13. @skip
作用: 跳过测试用例
适用场景:
- 未完成的测试
- 环境依赖未满足
- 已知问题临时跳过
import unittest
class TestCases(unittest.TestCase):
@unittest.skip("待实现")
def test_feature(self):
self.fail("未实现")
if __name__ == '__main__':
unittest.main()
总结表格
装饰器 | 模块 | 适用场景 | 版本要求 |
---|---|---|---|
@property | 内置 | 属性访问控制 | 所有版本 |
@lru_cache | functools | 缓存优化 | 3.2+ |
@contextmanager | contextlib | 资源管理 | 2.5+ |
@dataclass | dataclasses | 数据类 | 3.7+ |
@abstractmethod | abc | 接口规范 | 3.0+ |
@cached_property | functools | 属性缓存 | 3.8+ |
@singledispatch | functools | 函数重载 | 3.4+ |