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

基于Pandas的产品库存程序菜单逻辑问题及优化咨询

修复后的库存管理程序代码

Got it, let's fix that flow issue and clean up the code at the same time. The main problem with your current code is that the menu logic is tangled up with the product input flow, and the class inheritance doesn't make sense (Inventory shouldn't inherit from Product—instead, it should manage a collection of Products). Here's the revised code that behaves as you want:

import pandas as pd

class Product:
    def __init__(self, product_id, price, quantity_on_hand):
        # 初始化单个产品的属性,参数直接传入更清晰
        self.id = product_id
        self.price = price
        self.quantity_on_hand = quantity_on_hand

class Inventory:
    def __init__(self):
        # Inventory维护产品的DataFrame,初始化空结构
        self.products_df = pd.DataFrame(columns=['ID', 'Price', 'Quantity On Hand'])
    
    def add_product(self):
        # 单独的添加产品逻辑
        try:
            product_id = int(input("Enter product ID: "))
            price = float(input("Enter product price: "))
            quantity = int(input("Enter quantity on hand: "))
            
            # 创建Product对象(可选,也可以直接添加到DataFrame)
            new_product = Product(product_id, price, quantity)
            
            # 追加到DataFrame(用concat替代append,避免版本兼容问题)
            self.products_df = pd.concat([
                self.products_df,
                pd.DataFrame([{
                    'ID': new_product.id,
                    'Price': new_product.price,
                    'Quantity On Hand': new_product.quantity_on_hand
                }])
            ], ignore_index=True)
            
            print("\nProduct added successfully! Current inventory:")
            print(self.products_df)
            print("="*60)
        except ValueError:
            print("Invalid input! Please enter numeric values for ID, price, and quantity.")
            print("="*60)
    
    def calculate_total_value(self):
        # 单独计算库存总价值的逻辑
        if self.products_df.empty:
            print("Inventory is empty! No value to calculate.")
        else:
            total_value = (self.products_df['Price'] * self.products_df['Quantity On Hand']).sum()
            print(f"\nTotal inventory value: ${total_value:.2f}")
        print("="*60)
    
    def show_menu(self):
        # 主菜单逻辑,循环处理用户选择
        while True:
            print("\nInventory Management System")
            print("1) Add a new product")
            print("2) Calculate total inventory value")
            print("3) Exit")
            
            try:
                option = int(input("Enter your choice: "))
                print("="*60)
                
                if option == 1:
                    self.add_product()
                elif option == 2:
                    self.calculate_total_value()
                elif option == 3:
                    print("Exiting the system...")
                    break
                else:
                    print("Invalid option! Please choose 1, 2, or 3.")
                    print("="*60)
            except ValueError:
                print("Invalid input! Please enter a number (1, 2, or 3).")
                print("="*60)

# 运行程序
if __name__ == "__main__":
    inventory = Inventory()
    inventory.show_menu()

关键修复点

  • 菜单与功能分离:把添加产品、计算价值、菜单显示拆成独立方法,选完选项2后会回到主菜单,不会直接跳转到产品输入
  • 修正类关系:Inventory不再继承Product,而是管理多个Product实例(或直接维护DataFrame),符合面向对象的单一职责原则
  • 输入验证:添加try-except块处理非数字输入,避免程序崩溃
  • 移除递归:原代码的递归调用容易导致栈溢出,改用循环处理菜单选择更安全
  • 兼容Pandas版本:用pd.concat替代即将弃用的append方法,避免版本兼容问题

代码优化建议

  • 命名规范:遵循PEP8标准,类名用大驼峰(Product、Inventory),变量名用小蛇形(quantity_on_hand),提升代码可读性
  • 数据结构灵活选择:如果不需要Pandas的统计功能,用列表存储Product对象会更轻量;如果需要后续的筛选、排序等操作,Pandas是很好的选择
  • 持久化扩展:可以添加保存/加载库存数据的功能(比如保存到CSV文件),避免程序退出后数据丢失
  • 产品重复检查:添加逻辑防止重复添加相同ID的产品,或者允许更新现有产品的数量/价格
  • 格式化输出:对库存表格和数值进行格式化,让输出更美观(比如价格保留两位小数)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 08:32:35