2017-09-15 59 views
-3
class Item: 
    def __init__(self, code, desc, price, quantity): 
     self.__code = code    # the item code 
     self.__description = desc  # the item description 
     self.__price = price   # the item unit price 
     self.__quantity = quantity  # the number of item available 

    def getCode(self): 
     return self.__code 

    def setCode(self, code): 
     self.__code = code; 

    def getDescription(self): 
     return self.__description 

    def setDescription(self, desc): 
     self.__description = desc 

    def getPrice(self): 
     return self.__price 

    def setPrice(self, price): 
     self.__price = price 

    def getQuantity(self): 
     return self.__quantity 

    def setQuantity(self, quantity): 
     self.__quantity = quantity 

    def __repr__(self): 
     return 'Item({0}, {1}, {2}, {3})'.format(self.__code, self.__description, self.__price, self.__quantity)  

    def __str__(self): 
     return '{0}, {1}, {2}, {3}'.format(self.__code, self.__description, str(self.__price), str(self.__quantity)) 

# This function displays all the items on sale. 
    def display_items(self): 
     for i in range(len(self.__items)): 
      if self.__items[i] 
      print(self.__items[i]) 

BC001, Fresh toast bread white (700g), 3.99, 20 
BC002, Low-fat milk (2 liter), 4.8, 10 
BC003, V-energy drink, 2.75, 10 
BC005, Coca-Cola (300 ml), 2.5, 10 
BC006, Pineapple, 3.6, 6 
BC007, Mango, 1.89, 4 
BC008, Snickers chocolate bar, 1.8, 20 
BC009, Broccoli, 1.47, 11 
BC010, Washed Potato (2.5kg), 2.98, 7 
BC011, Good-morning cereal, 5.6, 10 
BC012, Rose apple (1.5kg bag), 4.98, 5 
BC013, Avocado (4pk), 4.99, 5 
BC014, Bananas (850g bag), 2.96, 4 
BC015, Kiwi fruit green (1kg), 2.45, 10 
BC016, Rock melon, 7.98, 2 
BC017, Lettuce, 2.99, 12 
BC018, Chocolate block (200g), 3.59, 10 
BC020, Parsley curly, 1.99, 6 
BC021, Grapefruit 1kg, 3.99, 7 

請注意,您應該只顯示數量值大於零的項目。也就是說,如果商品缺貨(其數量值爲0),則不應將其列爲可售商品。例如,在上面的輸出中,項目'BC004,新鮮大蒜(450g)'未被顯示。我不懂如何編寫display_items函數

+0

請上傳您所遇到的具體問題。你應該先嚐試一下。 – user3151902

+0

但它已經寫入了...... –

+1

最後一段的內容如同家庭作業的一部分,不是對您遇到的問題的描述。 – Barmar

回答

1

你想創建一個類變量和類方法:

class Item: 

    instances = [] 

    @classmethod 
    def display_all(cls): 
     for item in cls.instances: 
      if item.getQuantity() > 0: 
       print(item) 

    def __init__(self, code, desc, price, quantity): 
     Item.instances.append(self) 
     ... 

    ... 
+0

@jag它有幫助嗎?如果有幫助,不要忘記接受答案 –