【问题标题】:How do append an instance of a class?如何追加一个类的实例?
【发布时间】:2021-05-16 11:37:58
【问题描述】:

我希望创建一个(非常!)基本的库存管理系统

这是简介:

产品库存项目 - 创建一个管理 产品库存。创建一个具有价格、id、 和手头的数量。然后创建一个库存类,它保持 跟踪各种产品,并可以总结库存价值。

到目前为止,这是我的代码:

class Product:
    def __init__(self, id_num, price, quantity):
        self.price = price
        self.id_num = id_num
        self.quantity = quantity

class Inventory:
    def __init__(self):
        self.product_list = []
        
    def add_item(self):
        id_num = int(input('Enter id: '))
        price = int(input('Enter price: '))
        quantity = int(input('Enter quantity: '))
        self.product_list.append(Product(id_num, price, quantity))

我不明白如何在测试中将产品类的实例附加到产品列表中。我觉得我很遥远。任何帮助将不胜感激!

【问题讨论】:

  • 这段代码似乎完全符合您的要求 - 除了您没有显示任何创建 Inventory 对象然后在其上调用 .add_item() 的示例。你的问题到底是什么?
  • 你完全理解你目前掌握的代码吗?

标签: python python-3.x


【解决方案1】:

代码很好。你只需要执行:)

看看这个示例,我刚刚修改了输入并制作了静态值以便快速执行:

class Product:
    def __init__(self, id_num, price, quantity):
        self.price = price
        self.id_num = id_num
        self.quantity = quantity

class Inventory:
    def __init__(self):
        self.product_list = []
        
    def add_item(self):
        id_num = 1 #int(input('Enter id: '))
        price = 100 #int(input('Enter price: '))
        quantity = 4 #int(input('Enter quantity: '))
        self.product_list.append(Product(id_num, price, quantity))


inv = Inventory()
inv.add_item()
print(inv.product_list[0].price)

你应该得到100的打印结果,这是物品的价格

【讨论】:

  • 啊啊啊啊!我在测试时意识到我在做 test_inv = Inventory,而不是 test_Inv = Inventory()。感谢您的帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-13
  • 2020-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多