You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中实现购物车按商品数量计算折扣后总价

解决Cart类get_total_price方法的实现问题

问题分析

你的代码存在两处关键问题:

  • 参数传递错误:Cart类的__init__使用了可变位置参数*products_list,但创建实例时直接传入了元组products,导致self.products_list变成嵌套元组,无法正确遍历产品。
  • 方法逻辑缺失:get_total_price方法未实现遍历产品、获取属性并计算折扣的逻辑。

修正后的完整代码

class Product:
    
    def __init__(self, name, price, count):
        self.name = name
        self.price = price
        self.count = count


class Cart:
    
    def __init__(self, *products_list):
        self.products_list = products_list
    
    def get_total_price(self):
        total = 0.0
        for product in self.products_list:
            # 根据商品数量匹配对应折扣率
            if product.count > 20:
                discount = 0.5
            elif product.count >= 20:
                discount = 0.3
            elif product.count >= 10:
                discount = 0.2
            elif product.count >=7:
                discount = 0.1
            elif product.count >=5:
                discount = 0.05
            else:
                discount = 0  # 数量<5无折扣
            # 累加单个商品的折扣后总价
            total += product.price * product.count * (1 - discount)
        return total

        
products = (Product('p1',10,4),
Product('p2',100,5),
Product('p3',200,6),
Product('p4',300,7),
Product('p5',400,9),
Product('p6',500,10),
Product('p7',1000,20))
# 解包元组,将每个Product实例作为独立参数传入Cart
cart = Cart(*products)
print(cart.get_total_price())  # 输出24785.0

关键逻辑说明

  1. 访问产品属性:直接通过product.price和product.count即可获取每个Product实例的属性值,因为这些属性在Product类的__init__中已被赋值为实例属性。
  2. 折扣判断顺序:从最高折扣条件开始判断(先检查>20,再依次向下),确保每个数量区间匹配正确的折扣率。
  3. 总价计算:单个商品的折扣后价格为单价 × 数量 × (1 - 折扣率),将所有商品的该值累加得到最终总价。

内容的提问来源于stack exchange,提问作者Volodymyr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 03:10:29