簡體   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