2017-09-15 143 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它有帮助吗?如果有帮助,不要忘记接受答案 –