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

Python ShoppingCart类remove与修改数量方法故障排查求助

购物车remove_item与modify_item方法修复方案

原代码核心问题梳理

  1. remove_item方法逻辑混乱

    • 参数是商品名字符串,但循环里用item作为遍历变量,覆盖了入参
    • 错误地将列表self.items和对象item做比较,应该对比对象的item_name属性
    • 删除时用对象当索引,导致类型错误
    • 遍历过程中每遇到不匹配的项就打印提示,而非遍历完确认找不到才打印
  2. modify_item方法与执行逻辑缺失

    • 直接用对象item判断是否在列表中,实际应该按商品名称匹配
    • 错误修改item.quantity,实际属性名是item_quantity
    • execute_menu中把修改数量的选项错写成了i(重复了描述输出选项),且未调用modify_item方法
  3. 其他小问题

    • print_descriptions中笔误写成item.item.name,应为item.item_name
    • 修改数量时输入的item_quantity未转成整数

修正后的完整代码

class ItemToPurchase():
    def __init__(self):
        self.item_description = 'none'
        self.item_name = 'none'
        self.item_price= 0
        self.item_quantity = 0

    def print_item_description(self):
        print(f'{self.item_name}: {self.item_description}')

class ShoppingCart():
    def __init__(self, customer_name='none', current_date='January 1, 2016'):
        self.customer_name = customer_name
        self.current_date = current_date
        self.items = []

    def add_item(self, item ):
        ''' Adds an item to cart_items list. Has parameter of type ItemToPurchase. Does not return anything. '''
        self.items.append(item)

    def remove_item(self, item_name ):
        ''' Removes item from cart_items list. Has a string (an item's name) parameter. Does not return anything.
            If item name cannot be found, output this message: Item not found in cart. Nothing removed. '''
        delete = False
        # 遍历列表时用不同变量名,避免覆盖入参
        for idx, cart_item in enumerate(self.items):
            if cart_item.item_name == item_name:
                del self.items[idx]
                delete = True
                break  # 找到后立即退出循环
        if not delete:
            print("Item not found in cart. Nothing removed.")

    def modify_item(self, item, new_quantity):
        '''Modifies an item's quantity. Has a parameter of type ItemToPurchase. Does not return anything.
            If item can be found (by name) in cart, modify item in cart.'''
        found = False
        for cart_item in self.items:
            if cart_item.item_name == item.item_name:
                cart_item.item_quantity = new_quantity
                found = True
                break
        if not found:
            print("Item not found in cart. Nothing modified.")

    def get_num_items_in_cart(self):
        '''Returns quantity of all items in cart. Has no parameters.'''
        num_items = 0
        for item in self.items:
            num_items += item.item_quantity
        return num_items

    def get_cost_of_cart(self):
        '''Determines and returns the total cost of items in cart. Has no parameters.'''
        return sum(item.item_price * item.item_quantity for item in self.items)

    def print_total(self):
        '''Outputs total of objets in cart.
        If cart is empty, outputs this message: CART IS EMPTY.'''
        print(f"{self.customer_name}'s Shopping Cart - {self.current_date}")
        number_items = self.get_num_items_in_cart()
        print(f'Number of Items: {number_items}\n')
        total_cost = self.get_cost_of_cart()
        if total_cost == 0:
            print("SHOPPING CART IS EMPTY\n")
            print(f'Total: ${total_cost}')
            return False
        else:
            for item in self.items:
                item_cost = item.item_quantity * item.item_price
                print(f'{item.item_name} {item.item_quantity} @ ${item.item_price} = ${item_cost}')
            print()
            total_cost = self.get_cost_of_cart()
            print(f'Total: ${total_cost}')

    def print_descriptions(self):
        ''' Outputs each item's description'''
        print(f"{self.customer_name}'s Shopping Cart - {self.current_date}\n")
        print("Item Descriptions")  # 把标题移到循环外,避免重复打印
        for item in self.items:
            # 修正笔误:item.item.name -> item.item_name
            print(f'{item.item_name}: {item.item_description}')

def print_menu():
    print("MENU\na - Add item to cart\nr - Remove item from cart\nc - Change item quantity\ni - Output items' descriptions\no - Output shopping cart\nq - Quit\n")

def execute_menu(choice , shopping_cart):
    if choice == "o":
        print("OUTPUT SHOPPING CART")
        shopping_cart.print_total()

    elif choice == "i":
        print("OUTPUT ITEMS' DESCRIPTIONS")
        shopping_cart.print_descriptions()

    elif choice == "a":
        print("ADD ITEM TO CART\nEnter the item name:")
        item_name = input()
        print("Enter the item description:")
        item_description = input()
        print("Enter the item price:")
        item_price = int(input())
        print("Enter the item quantity:")
        item_quantity = int(input())
        New_item = ItemToPurchase()
        New_item.item_name = item_name
        New_item.item_price = item_price
        New_item.item_quantity = item_quantity
        New_item.item_description = item_description
        shopping_cart.add_item(New_item)

    elif choice =="r":
        print("REMOVE ITEM FROM CART\nEnter name of item to remove:")
        removed_item = input()
        shopping_cart.remove_item(removed_item)

    elif choice == "c":  # 修正选项名,从i改为c
        '''Implement Change item quantity menu option in execute_menu(). Hint: Make new ItemToPurchase object before using ModifyItem() method. '''
        print("CHANGE ITEM QUANTITY\nEnter the item name:")
        temp_item = ItemToPurchase()
        temp_item.item_name = input()
        print("Enter the new quantity:")
        # 转换为整数类型
        new_quantity = int(input())
        # 调用modify_item方法
        shopping_cart.modify_item(temp_item, new_quantity)

if __name__ == "__main__":
    shopping_cart = ShoppingCart()
    print("Enter customer's name:")
    shopping_cart.customer_name = input()

    print("Enter today's date:")
    shopping_cart.current_date = input()
    print()
    print(f"Customer name: {shopping_cart.customer_name}\nToday's date: {shopping_cart.current_date}")
    print()

    print_menu()
    print("Choose an option:")
    while True:
        choice = input().strip()  # 去除输入的空格

        if choice in "arcioq":
            if choice == 'q':
                break
            else:
                execute_menu(choice, shopping_cart)
                print()
                print_menu()
        print("Choose an option:")

关键修改点说明

  • remove_item:用enumerate获取索引,按商品名匹配,找到后直接删除并退出循环,遍历完未找到才打印提示
  • modify_item:遍历购物车按商品名匹配,修改对应对象的item_quantity属性
  • execute_menu:修正修改数量的选项为c,补充调用modify_item的逻辑,将输入的数量转为整数
  • print_descriptions:修正属性名笔误,将描述标题移到循环外避免重复打印

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 11:15:58