当前位置: 首页 > news >正文

类间@符号装饰器

在Python中,使用装饰器关联两个类是一种高级技巧,可以通过动态修改类属性、方法或实现设计模式来实现类间的交互。以下是基于搜索结果的五种典型实现方式及案例:


1. 类装饰器动态添加其他类的方法或属性

通过装饰器将另一个类的方法或属性注入到目标类中,实现功能复用(参考网页2和网页3)。

案例:将日志工具类的方法注入到业务类

class LoggerUtils:@staticmethoddef log_activity(func):def wrapper(self, *args, **kwargs):print(f"[LOG] {self.__class__.__name__} 执行 {func.__name__}")return func(self, *args, **kwargs)return wrapperdef add_logging(cls):# 注入日志装饰器到目标类的所有方法for name, method in cls.__dict__.items():if callable(method) and not name.startswith('__'):setattr(cls, name, LoggerUtils.log_activity(method))return cls@add_logging
class UserService:def create_user(self, name):print(f"创建用户: {name}")service = UserService()
service.create_user("Alice")
# 输出:
# [LOG] UserService 执行 create_user
# 创建用户: Alice

2. 装饰者模式包装类实例

通过装饰器类包装另一个类的实例,扩展其行为(参考网页4、网页6和网页7)。

案例:权限控制装饰器包装用户操作类

class UserOperation:def delete_file(self, filename):print(f"删除文件: {filename}")class PermissionDecorator:def __init__(self, operation, role):self._operation = operationself.role = roledef delete_file(self, filename):if self.role == "admin":self._operation.delete_file(filename)else:print("权限不足")# 装饰器关联两个类
user_op = UserOperation()
decorated_op = PermissionDecorator(user_op, "user")
decorated_op.delete_file("data.txt")  # 输出: 权限不足

3. 类注册装饰器

通过装饰器将类注册到另一个类的全局容器中,实现类间关联(参考网页2和网页3)。

案例:插件系统注册

class PluginRegistry:_plugins = {}@classmethoddef register(cls, name):def decorator(plugin_cls):cls._plugins[name] = plugin_clsreturn plugin_clsreturn decorator@PluginRegistry.register("excel_parser")
class ExcelParser:def parse(self, file):print("解析Excel文件")@PluginRegistry.register("csv_parser")
class CsvParser:def parse(self, file):print("解析CSV文件")# 通过注册类调用其他类
parser = PluginRegistry._plugins["excel_parser"]()
parser.parse("data.xlsx")  # 输出: 解析Excel文件

4. 跨类方法装饰

在一个类中定义装饰器,用于修饰另一个类的方法(参考网页9)。

案例:数据验证装饰器用于模型类

class Validator:@staticmethoddef validate_int(func):def wrapper(self, value):if not isinstance(value, int):raise ValueError("必须为整数")return func(self, value)return wrapperclass DataModel:@Validator.validate_intdef set_value(self, value):self.value = valuemodel = DataModel()
model.set_value(10)  # 正常执行
model.set_value("abc")  # 抛出 ValueError

5. 装饰器实现适配器模式

通过装饰器将一个类的接口转换为另一个类兼容的接口(参考网页5)。

案例:旧支付接口适配新系统

class OldPaymentSystem:def pay_in_dollars(self, amount):print(f"支付 ${amount}")class PaymentAdapter:def __init__(self, old_system):self.old_system = old_systemdef pay_in_rmb(self, amount):self.old_system.pay_in_dollars(amount / 6.5)def adapt_old_payment(cls):def decorator(new_cls):new_cls.old_system = cls()return new_clsreturn decorator@adapt_old_payment(OldPaymentSystem)
class NewPaymentSystem:def pay(self, currency, amount):if currency == "CNY":self.old_system.pay_in_rmb(amount)else:raise ValueError("不支持的货币")payment = NewPaymentSystem()
payment.pay("CNY", 650)  # 调用旧系统方法,输出: 支付 $100.0

核心设计原则

  1. 开放-封闭原则:不修改原有类代码,通过装饰器扩展功能(参考网页4)。
  2. 单一职责原则:将装饰逻辑与业务逻辑分离(参考网页6)。
  3. 组合优于继承:通过装饰器组合实现灵活的功能叠加(参考网页7)。

适用场景总结

场景技术方案案例引用
动态添加功能类装饰器注入方法/属性
接口适配适配器模式装饰器
权限控制装饰者模式包装实例
系统插件化注册类装饰器
跨类方法增强静态方法装饰器

通过合理选择装饰器模式,可以实现类间低耦合、高灵活性的交互。

http://www.xdnf.cn/news/174133.html

相关文章:

  • php:实现窗口选择数据,并返回给主页面
  • Alibaba Druid 完整配置与 Keepalive 优化指南
  • 前端分页与瀑布流最佳实践笔记 - React Antd 版
  • 前端-介绍一个好用的波浪背景生成器
  • 《操作系统真象还原》第十章(1)——输入输出系统
  • Java 设计模式
  • ADS基本操作之AC仿真
  • rt-linux下的D状态的堆栈抓取及TASK_RTLOCK_WAIT状态
  • AVFormatContext 再分析
  • 手写SpringMVC(基本框架)
  • 视觉“解锁”触觉操控:Franka机器人如何玩转刚柔物体?
  • matlab simulink中理想变压激磁电流容易有直流偏置的原因分析。
  • C++ AVL树的实现
  • 日语学习-日语知识点小记-进阶-JLPT-N2阶段(9):语法单词
  • 目标跟踪最新文章阅读列表
  • 极简主义在 UI 设计中的应用与实践:打造简洁高效界面
  • 基于定制开发开源AI智能名片S2B2C商城小程序的会员存量池构建策略研究
  • MCP:人工智能时代的HTTP?探索AI通信新标准
  • cached-property - 类属性缓存装饰器
  • 如何让自己的博客可以在百度、谷歌、360上搜索到(让自己写的CSDN博客可以有更多的人看到)
  • Win11 配置 Git 绑定 Github 账号的方法与问题汇总
  • 有效的字母异位词
  • 10 DPSK原始对话记录
  • ultralytics-YOLO模型在windows环境部署
  • Redis 笔记(三)-Redis 基本知识及五大数据类型
  • day004
  • PostgreSQL WAL 幂等性详解
  • PH热榜 | 2025-04-26
  • 论文速报《ChatBEV:理解BEV地图的视觉语言模型新突破》
  • uniapp自定义一个选择年月日时分的组件。