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

python: Interpreter Pattern

项目结构:

image

 珠宝行业适用场景:

 
  • 珠宝价格规则计算(黄金克价 + 工费 + 钻石溢价)
  • 珠宝真伪 / 等级校验规则(金纯度≥99.9% + 钻石净度≥VS1)
  • 珠宝筛选规则(按材质、品类、价格区间快速匹配)
 

珠宝行业完整实例

 
我们实现:珠宝价格 / 属性规则解释器
 
支持规则:
 
  1. 基础金价计算:黄金价格 = 克重 × 基础金价 + 工费
  2. 组合规则:黄金纯度达标 且 钻石净度达标
  3. 筛选规则:价格 ≥ 5000 且 材质是 铂金
# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Interpreter Pattern 解释器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/28 21:43 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : jewelry_context.pyfrom dataclasses import dataclass@dataclass
class JewelryContext:"""珠宝上下文:存储所有珠宝属性"""name: str = ""material: str = ""weight: float = 0.0purity: float = 0.0price: float = 0.0clarity: str = ""

  

# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Interpreter Pattern 解释器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/28 21:50 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : base_expression.pyfrom abc import ABC, abstractmethod
from Interpreter.context.jewelry_context import JewelryContextclass BaseExpression(ABC):"""职责:抽象表达式(所有规则必须实现)"""@abstractmethoddef interpret(self, context: JewelryContext) -> bool | float:"""解释规则:返回判断结果 或 计算结果:param context::return:"""pass# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Interpreter Pattern 解释器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/28 21:54 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : calculate_exp.pyfrom Interpreter.expression.base_expression import BaseExpression
from Interpreter.context.jewelry_context import JewelryContextclass GoldPriceExpression(BaseExpression):"""原子规则:黄金价格计算(可扩展钻石 / 宝石)"""def __init__(self, base_price: float, craft_fee: float):""":param base_price::param craft_fee:"""self.base_price = base_priceself.craft_fee = craft_feedef interpret(self, context: JewelryContext) -> float:""":param context::return:"""total = context.weight * self.base_price + self.craft_feereturn round(total, 2)# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Interpreter Pattern 解释器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/28 21:52 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : compare_exp.pyfrom Interpreter.expression.base_expression import BaseExpression
from Interpreter.context.jewelry_context import JewelryContextclass GreaterThanExpression(BaseExpression):"""原子规则:数值比较 >="""def __init__(self, field: str, threshold: float):""":param field::param threshold:"""self.field = fieldself.threshold = thresholddef interpret(self, context: JewelryContext) -> bool:""":param context::return:"""value = getattr(context, self.field, 0.0)return value >= self.threshold# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Interpreter Pattern 解释器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/28 21:53 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : material_exp.pyfrom Interpreter.expression.base_expression import BaseExpression
from Interpreter.context.jewelry_context import JewelryContextclass MaterialMatchExpression(BaseExpression):"""原子规则:材质匹配"""def __init__(self, material: str):""":param material:"""self.material = materialdef interpret(self, context: JewelryContext) -> bool:""":param context::return:"""return context.material == self.material# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Interpreter Pattern 解释器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/28 21:55 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : and_exp.pyfrom Interpreter.expression.base_expression import BaseExpression
from Interpreter.context.jewelry_context import JewelryContextclass AndExpression(BaseExpression):"""组合规则:AND"""def __init__(self, exp1: BaseExpression, exp2: BaseExpression):""":param exp1::param exp2:"""self.exp1 = exp1self.exp2 = exp2def interpret(self, context: JewelryContext) -> bool:""":param context::return:"""return self.exp1.interpret(context) and self.exp2.interpret(context)# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Interpreter Pattern 解释器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/28 21:55 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : or_exp.pyfrom Interpreter.expression.base_expression import BaseExpression
from Interpreter.context.jewelry_context import JewelryContextclass OrExpression(BaseExpression):"""组合规则:OR"""def __init__(self, exp1: BaseExpression, exp2: BaseExpression):""":param exp1::param exp2:"""self.exp1 = exp1self.exp2 = exp2def interpret(self, context: JewelryContext) -> bool:""":param context::return:"""return self.exp1.interpret(context) or self.exp2.interpret(context)

  

# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Interpreter Pattern 解释器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/28 21:56 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : jewelry_rule_service.pyfrom Interpreter.context.jewelry_context import JewelryContext
from Interpreter.expression.base_expression import BaseExpressionclass JewelryRuleService:"""业务服务层:对外提供规则解释能力(解耦调用方)"""@staticmethoddef evaluate(expression: BaseExpression, context: JewelryContext) -> bool | float:"""执行规则解释:param expression::param context::return:"""return expression.interpret(context)

  

调用:

# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Interpreter Pattern 解释器模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/4/28 22:01 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : InterpreterBll.py
'''
Interpreter /
├── cmd/
│   └── main.go
├── internal/  # 内部业务包(外部不可引用)
│   ├── context/   # 上下文环境(变量容器)
│   │   └── context.go
│   ├── expression/ # 解释器表达式核心(终结符+非终结符)
│   │   └── expr.go
│   ├── parser/ # 语法解析器
│   │   └── parser.go
│   └── service/   # 业务服务层
│       └── price_service.go
└── go.mod'''
from Interpreter.context.jewelry_context import JewelryContext
from Interpreter.expression.terminal.compare_exp import GreaterThanExpression
from Interpreter.expression.terminal.material_exp import MaterialMatchExpression
from Interpreter.expression.terminal.calculate_exp import GoldPriceExpression
from Interpreter.expression.non_terminal.and_exp import AndExpression
from Interpreter.service.jewelry_rule_service import JewelryRuleServiceclass InterpreterBll(object):""""""def demo(self):""":return:"""# 1. 构建珠宝上下文jewelry = JewelryContext(name="999足金戒指",material="黄金",weight=5.2,purity=99.9,clarity="VS1")# 2. 规则服务service = JewelryRuleService()# ------------------- 规则1:计算黄金价格 -------------------price_exp = GoldPriceExpression(base_price=450, craft_fee=150)price = service.evaluate(price_exp, jewelry)print(f"售价:{price} 元")# ------------------- 规则2:高品质黄金 -------------------high_purity = GreaterThanExpression("purity", 99.9)is_gold = MaterialMatchExpression("黄金")high_quality_exp = AndExpression(high_purity, is_gold)result = service.evaluate(high_quality_exp, jewelry)print(f"是否高品质黄金:{result}")# ------------------- 规则3:高端珠宝 -------------------platinum = JewelryContext(material="铂金", price=6800)high_price = GreaterThanExpression("price", 5000)is_platinum = MaterialMatchExpression("铂金")filter_exp = AndExpression(high_price, is_platinum)print(f"是否高端珠宝:{service.evaluate(filter_exp, platinum)}")

  

输出:

image

 

http://www.jsqmd.com/news/716034/

相关文章:

  • 深度学习模型优化与实时推理技术解析
  • AppleRa1n 终极指南:3步离线绕过iOS 15-16激活锁
  • LLM推理优化:判别式验证技术解析与实践
  • FPGA新手避坑指南:用Verilog在Spartan-6上搞定IS62LV256 SRAM读写(附完整代码)
  • 3美元WiFi 6 USB网卡评测:AIC8800芯片性价比解析
  • 【必收藏】2026年大模型应用开发工程师趋势解析,小白程序员必看!
  • 3分钟永久激活IDM:开源脚本实现无限期试用的完整指南
  • 2026 绍兴二手车行业 TOP1 深度拆解|环宇名车:诚信与品质铸就本地二手车标杆 - 花开富贵112
  • AG-BPE:NLP字节对编码算法的评估框架与数据集优化
  • [FRP]Windows 安装 frpc 客户端,以及P2P方式ssh配置
  • 解锁论文降重新姿势:书匠策AI,你的学术减负小能手!
  • AgenticMarket:MCP生态的“应用商店”,一键安装AI助手扩展
  • 群体神经网络:分布式API调用与弹性计算新范式
  • claw-memory-os:专为资源受限MCU设计的轻量级RTOS内核解析
  • 3分钟搞定IDM永久激活:简单实用的免费使用终极指南
  • 机洗染色惊魂记:从紧急拯救衣物到日常防串色的实战全记录 - 行业分析师666
  • 数据结构选型指南场景与性能分析
  • HunyuanVideo-Foley保姆级教程:WebUI中实时调整采样温度与top-p参数
  • 内存健康守护神:如何用Memtest86+彻底检测电脑内存故障
  • 手把手教你调参:MATLAB中ellipord和ellipap函数设计椭圆滤波器的完整避坑指南
  • 小程序商城搭建平台对比:功能、成本与选择分析
  • 2026永辉超市卡回收平台TOP榜:鼎鼎收15年深耕四项五星强势领跑,闲置变现安全省心 - 鼎鼎收礼品卡回收
  • Java 25 外部函数接口增强:仅剩72小时!OpenJDK 25正式版冻结前必须掌握的3个@ClangBinding兼容性开关
  • 从《我的世界》到自动驾驶:聊聊包围盒算法(AABB/OBB)的跨界应用
  • MPR121电容触摸传感器避坑指南:与Arduino UNO驱动WS2812时常见的3个问题及解决
  • 一文读懂AI七大核心概念,打造你的智能AI员工,大模型技术全景图谱2026
  • 微信语音导出mp3全攻略:手机免电脑、在线工具、格式工厂三种方法实测对比
  • 为 esp-idf 安装管理 改进代码
  • 告别多图烦恼:用pixelSplat和3D Gaussian Splats,两张照片就能玩转3D重建(附代码实战)
  • 销售易CRM:B2B企业如何有效缩短商机挖掘周期?