python基础入门:5.4实战:电商商品管理系统

embedded/2025/2/11 8:46:47/
python">"""
电商商品管理系统核心模块
包含商品管理、购物车操作、折扣策略和库存控制功能
"""class Product:"""商品实体类,负责库存管理"""def __init__(self, sku: str, name: str, price: float, stock: int):"""初始化商品:param sku: 商品唯一标识:param name: 商品名称:param price: 商品单价:param stock: 库存数量"""self.sku = skuself.name = nameself.price = priceself._stock = stockself.discount_strategy = None  # 折扣策略@propertydef stock(self) -> int:"""实时库存查询"""return self._stockdef apply_discount(self, strategy: callable):"""应用折扣策略"""self.discount_strategy = strategydef current_price(self) -> float:"""计算当前折扣价"""if self.discount_strategy:return self.discount_strategy(self.price)return self.pricedef update_stock(self, quantity: int) -> None:"""更新库存"""if self._stock + quantity < 0:raise ValueError("库存不足")self._stock += quantityclass ShoppingCart:"""购物车系统,支持多商品操作"""def __init__(self):self.items = {}  # {Product: quantity}self.coupons = []  # 全场优惠券def add_item(self, product: Product, quantity: int = 1) -> None:"""添加商品到购物车"""if quantity <= 0:raise ValueError("数量必须大于0")if product.stock < quantity:raise InsufficientStockError(f"商品 {product.name} 库存不足")product.update_stock(-quantity)self.items[product] = self.items.get(product, 0) + quantitydef remove_item(self, product: Product, quantity: int = 1) -> None:"""移除购物车中的商品"""current_qty = self.items.get(product, 0)if current_qty < quantity:raise ValueError("移除数量超过购物车中数量")product.update_stock(quantity)if current_qty == quantity:del self.items[product]else:self.items[product] -= quantitydef apply_coupon(self, coupon: callable):"""应用全场优惠券"""self.coupons.append(coupon)def calculate_total(self) -> float:"""计算订单总金额"""subtotal = sum(p.current_price() * qty for p, qty in self.items.items())# 应用优惠券折扣for coupon in self.coupons:subtotal = coupon(subtotal)return max(subtotal, 0)  # 金额不低于0def checkout(self) -> None:"""执行结算操作"""if not self.items:raise EmptyCartError("购物车为空")# 实际支付和订单生成逻辑print(f"订单提交成功,总金额:{self.calculate_total():.2f}")self.items.clear()self.coupons.clear()class InsufficientStockError(Exception):"""库存不足异常"""passclass EmptyCartError(Exception):"""空购物车异常"""pass# 折扣策略工厂
class DiscountStrategies:"""预定义折扣策略"""@staticmethoddef percentage_off(percent: float) -> callable:"""百分比折扣"""return lambda price: price * (1 - percent/100)@staticmethoddef fixed_discount(amount: float) -> callable:"""固定金额折扣"""return lambda price: max(price - amount, 0)@staticmethoddef bulk_discount(threshold: int, discount: float) -> callable:"""批量折扣"""return lambda price, quantity: price * quantity * (1 - discount/100) if quantity >= threshold else price * quantity# 优惠券示例
def christmas_coupon(total: float) -> float:"""圣诞全场满减"""if total >= 200:return total - 50return totaldef new_user_coupon(total: float) -> float:"""新用户首单折扣"""return total * 0.9# 使用示例
if __name__ == "__main__":# 创建商品iphone = Product("A001", "iPhone 15", 7999.0, 10)headphones = Product("A002", "蓝牙耳机", 399.0, 50)# 设置折扣iphone.apply_discount(DiscountStrategies.percentage_off(10))  # 9折headphones.apply_discount(DiscountStrategies.fixed_discount(100))  # 立减100# 初始化购物车cart = ShoppingCart()cart.add_item(iphone, 2)cart.add_item(headphones, 3)# 应用优惠券cart.apply_coupon(christmas_coupon)cart.apply_coupon(new_user_coupon)# 显示总金额print(f"折后总价: {cart.calculate_total():.2f}")  # 输出:折后总价: 14391.36# 结算订单try:cart.checkout()except EmptyCartError as e:print(e)

系统设计要点说明

  1. 库存管理机制

    • 实时库存追踪:在商品类中使用_stock私有属性
    • 原子操作:update_stock方法保证库存增减的原子性
    • 预占库存:添加购物车时立即扣减库存
  2. 折扣策略系统

    • 策略模式实现:支持商品级折扣和全场优惠券
    • 灵活组合:可叠加多种折扣策略
    • 预置策略工厂:提供常用折扣模板
  3. 购物车核心功能

    • 多商品管理:使用字典存储商品与数量
    • 异常处理:自定义库存不足和空购物车异常
    • 结算流程:清空购物车同时重置优惠券
  4. 价格计算逻辑

    python"># 价格计算公式
    总价 = Σ(商品折扣价 × 数量)
    最终价 = 优惠券1(优惠券2(总价))
    

高级功能扩展建议

  1. 库存预警系统

    python">class Product(Product):def __init__(self, *, low_stock_threshold=5, **kwargs):super().__init__(**kwargs)self.low_stock_threshold = low_stock_thresholddef check_stock_level(self):if self.stock < self.low_stock_threshold:alert_msg = f"库存预警:{self.name} 仅剩 {self.stock} 件"InventoryAlert.send_alert(alert_msg)
    
  2. 组合商品支持

    python">class ProductBundle:"""组合商品类"""def __init__(self, products: list[Product], bundle_price: float):self.products = productsself.bundle_price = bundle_pricedef current_price(self):return self.bundle_price
    
  3. 订单历史记录

    python">class ShoppingCart(ShoppingCart):def __init__(self):super().__init__()self.order_history = []def checkout(self):order = {"items": self.items.copy(),"total": self.calculate_total(),"timestamp": datetime.now()}self.order_history.append(order)super().checkout()
    

性能优化方案

  1. 使用__slots__提升对象性能

    python">class Product:__slots__ = ['sku', 'name', 'price', '_stock', 'discount_strategy']
    
  2. 缓存价格计算结果

    python">from functools import lru_cacheclass Product(Product):@lru_cache(maxsize=128)def current_price(self):return super().current_price()
    
  3. 使用Decimal处理金融计算

    python">from decimal import Decimalclass Product:def __init__(self, price: float):self.price = Decimal(str(price)).quantize(Decimal('0.00'))
    

http://www.ppmy.cn/embedded/161283.html

相关文章

【metersphere】创建的变量,在json携带数据的时候,不生效

在前置脚本中&#xff0c;定义变量 在请求体数据中&#xff0c;进行使用&#xff0c;json形式的数据&#xff0c; 在请求体中&#xff0c;进行使用 切换到json_schema 直接使用变量&#xff0c;传输成功

使用Chatbox与本地Deepseek-R1交互

在《deepseek本地部署和使用&#xff08;Linux虚拟机&#xff09;》中&#xff0c;我们使用Ollama部署了Deepseek-r1&#xff0c;并在《使用WebUI访问本地Deepseek&#xff08;Ollama集成Open WebUI&#xff09;》中介绍了&#xff0c;在Linux服务器端OllamaOpen WebUI的集成&a…

Visual Studio 2022 中使用 Google Test

要在 Visual Studio 2022 中使用 Google Test (gtest)&#xff0c;可以按照以下步骤进行&#xff1a; 安装 Google Test&#xff1a;确保你已经安装了 Google Test。如果没有安装&#xff0c;可以通过 Visual Studio Installer 安装。在安装程序中&#xff0c;找到并选择 Googl…

【新书速荐】《Information-Theoretic Radar Signal Processing(信息论雷达信号处理)》

引言 最近&#xff0c;由Yujie Gu 博士和 Yimin D. Zhang 教授主编的新书 Information-Theoretic Radar Signal Processing由 Wiley-IEEE Press 正式出版。 这是信息论雷达信号处理领域的首部专著&#xff0c;全书共分 14 章&#xff0c;汇集了来自学术界、工业界和政府机构的…

5.14.8 Function (ESipa): CancelSession

5.14.8 函数 (ESipa)&#xff1a;CancelSession 相关程序&#xff1a;配置文件下载和安装 函数提供商实体&#xff1a;eIM 说明&#xff1a; IPA 应调用此函数来请求取消正在进行的 RSP 会话。此决定可能源自 eIM 或 IPA&#xff0c;具体取决于发生故障的位置。eIM 可在 ESipa…

KTOR:高效的Linux横向移动与无文件落地HTTP服务扫描工具

地址:https://github.com/MartinxMax/KTOR 简介 KTOR 是一款专为 Linux 横向渗透设计的工具。通过该工具&#xff0c;您可以快速扫描内部 HTTP 服务&#xff0c;以便进一步进行网络渗透&#xff0c;且实现无文件落地扫描。 在CTF中通常需要利用本地其他端口HTTP服务或其他主…

json格式化html

<!DOCTYPE html> <html lang"zh-CN"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>JSON 格式化器</title><style>body …

Flink 内存模型各部分大小计算公式

Flink 的运行平台 如果 Flink 是运行在 yarn 或者 standalone 模式的话&#xff0c;其实都是运行在 JVM 的基础上的&#xff0c;所以首先 Flink 组件运行所需要给 JVM 本身要耗费的内存大小。无论是 JobManager 或者 TaskManager &#xff0c;他们 JVM 内存的大小都是一样的&a…