我有一個代碼,用於讀取庫存txt文件,該文件假設在用戶運行時顯示一個菜單。然而,在運行時的數量和費用相加列錯位:打印列表中的數據會出現錯位
Select an item ID to purchase or return:
ID Item Quantity Price
244 Large Cake Pan 7.00 19.99
576 Assorted Sprinkles 3.00 12.89
212 Deluxe Icing Set 6.00 37.97
827 Yellow Cake Mix 3.00 1.99
194 Cupcake Display Board 2.00 27.99
285 Bakery Boxes 7.00 8.59
736 Mixer 5.00 136.94
Enter another item ID or 0 to stop
這裏是我的代碼:
import InventoryFile
def readFile():
#open the file and read the lines
inventoryFile = open ('Inventory.txt', 'r')
raw_data = inventoryFile.readlines()
#remove the new line characters
clean_data = []
for item in raw_data:
clean_item = item.rstrip ('\n')
clean_data.append (clean_item)
#read lists into objects
all_objects = []
for i in range (0, len(clean_data), 4):
ID = clean_data [i]
item = clean_data [i+1]
qty = float (clean_data [i+2])
price = float (clean_data [i+3])
inventory_object = InventoryFile.Inventory (ID, item, qty, price)
all_objects.append (inventory_object)
return all_objects
def printMenu (all_data):
print()
print ('Select an item ID to purchase or return: ')
print()
print ('ID\tItem\t\t Quantity\t Price')
for item in all_data:
print (item)
print()
print ('Enter another item ID or 0 to stop')
def main():
all_items = readFile()
printMenu (all_items)
main()
我如何格式化輸出,這樣的數量和價格列正確對齊?
這裏是庫存類:
class Inventory:
def __init__ (self, new_id, new_name, new_stock, new_price):
self.__id = new_id
self.__name = new_name
self.__stock = new_stock
self.__price = new_price
def get_id (self):
return self.__id
def get_name (self):
return self.__name
def get_stock (self):
return self.__stock
def get_price (self):
return self.__price
def restock (self, new_stock):
if new_stock < 0:
print ('ERROR')
return False
else:
self.__stock = self.__stock + new_stock
return True
def purchase (self, purch_qty):
if (new_stock - purch_qty < 0):
print ('ERROR')
return False
else:
self.__stock = self.__stock + purch_qty
return True
def __str__ (self):
return self.__id + '\t' + self.__name + '\t' + \
format (self.__stock, '7.2f') + format (self.__price, '7.2f')
閱讀關於'str.format()',例如'打印('{:5} {:20} {:10} {:10}'。format('ID','Item','Quantity','Price'))' – AChampion
[Printing Lists as表格數據](http://stackoverflow.com/questions/9535954/printing-lists-as-tabular-data) – AChampion
另外,在Python中,你通常不會寫getters和setter,也不要使用double-下劃線名稱 - 強化,即。 '自我.__股票',除非你真的想/需要這種行爲。如果您想遵循「私有」變量的約定,只需使用'self.stock'或'self._stock'。 –