繁体   English   中英

如何将预定义的 class object 添加到列表中?

[英]How can I add a pre-defined class object to a list?

我正在开发一个 Udemy 项目,我们需要为具有价格、代码和数量的产品创建 class,然后使用 function 创建库存 class 以找到所有产品的总价格。 产品 class 似乎工作正常,但我真的很难弄清楚如何将对象添加到库存 class 中的列表中。 这是我到目前为止的代码:

inventory = []

# Define a Product class. Objects should have 3 variables for price, code, and quantity
class Product:
    
    def __init__(self, price=0.00, code='aaaa', quantity=0):
        self.price = price
        self.code = code
        self.quantity = quantity
    
    def __repr__(self):
        return f'Product({self.price!r}, {self.code!r}, {self.quantity!r})'
    
    def __str__(self):
        return f'The product code is: {self.code}'

# Define an inventory class and a function for calculating the total value of the inventory. 
class Inventory:    
    
    def __init__(self):
        self.products_list = []
    
    def add_product(self):
        self.products_list.append(Product(price, code, value))
        return self.products_list
        
    def total_value(self):
        return sum(product.price * product.quantity for product in self.products_list)

apple = Product(1.00, 'appl', 10)
orange = Product(1.50, 'orng', 10)
pear = Product(1.75, 'pear', 10)

def main():
    Inventory.add_product(apple)
    Inventory.add_product(orange)
    Inventory.add_product(pear)
    Inventory.total_value()

if __name__ == "__main__":
    main()

这是我得到的错误:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-116-972361fa1b80> in <module>
      1 if __name__ == "__main__":
----> 2     main()

<ipython-input-115-b55f02143572> in main()
      1 def main():
----> 2     Inventory.add_product(apple)
      3     Inventory.add_product(orange)
      4     Inventory.add_product(pear)
      5     Inventory.total_value()

<ipython-input-111-bbbfc35f0b7e> in add_product(self)
     25 
     26     def add_product(self):
---> 27         self.products_list.append(Product(price, code, value))
     28         return self.products_list
     29 

AttributeError: 'Product' object has no attribute 'products_list'

现在的障碍在于 add_product 方法。 我不知道如何将 append 加入列表。 我已经在网上看到了用户输入产品的解决方案,但我想使用预定义的解决方案,所以理论上你可以从 excel 表导入和导出。 任何帮助,将不胜感激。

我看到两个主要错误。 第一个是 class 方法和实例方法之间的混淆。 二是对数据流的困惑。

像产品一样,库存应该被实例化:您可能希望在不同的仓库或在不同的日子拥有单独的库存。 因此,就像您创建Product的实例一样:

apple = Product(1.00, 'appl', 10)

创建一个Inventory的实例,然后将产品添加到其中 - 而不是Inventory class:

inventory = Inventory()
inventory.add_product(apple)

add_product这样的实例方法必须接受一个额外的参数,通常命名为self ,来表示接收方法调用的 object。 您还传递了要添加的产品。 这意味着add_product方法应该采用两个arguments。 并且由于您已经传入了诸如apple之类的产品,因此add_product无需在其中构造另一个Product

def add_product(self, product):
    self.products_list.append(product)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM