2017-05-09 1 views
0

구매 또는 반환 할 제품 메뉴에서 항목을 선택할 수있는 인보이스 프로그램을 만들고 있습니다. 사용자가 원하는 항목 ID와 수량을 입력하면 프로그램은 inventory.txt 파일을 읽고 inventory.txt 파일을 대체 할 UpdatedInventory.txt 파일을 작성합니다. inventory.txt 파일은 다음과 같이 포맷 : 내 프로그램이 실행되면인벤토리 프로그램에서 txt 파일 업데이트 문제가 발생했습니다.

ID 
item 
stock 
price 

, 그것은 UpdatedInventory.txt 파일을 제대로 인쇄되지 않습니다. 여기에 많은 코드가 나와 함께있어.

제쳐두고 사용자가 만든 모든 구매가 하드 코딩되지 않고 목록에 추가 된 경우 코드를 단순화하는 것처럼 느껴집니다. 도와 주셔서 감사합니다! 여기

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 += new_stock 
      return True 

    def purchase (self, purch_qty): 
     if self.__stock >= purch_qty: 
      self.__stock -= purch_qty 
      return self.__stock 
     else: 
      print ('ERROR: Insufficient stock') 
      return False 

    def __str__ (self): 
     return self.__id + '\t' + self.__name + '\t' + \ 
     format (self.__stock, '7.2f') + format (self.__price, '7.2f') 

class TransactionItem (Inventory): 
    def __init__ (self, new_id, new_name, new_qty, new_price): 
     self.__qty = new_qty 
     Inventory.__init__(self, new_id, new_name, new_qty, new_price) 

    def get_id (self): 
     return self.__id 
    def set_id (self, new_id): 
     self.__id = new_id 
    def get_name (self): 
     return self.__name 
    def set_name (self, new_name): 
     self.__name = new_name 
    def get_qty (self): 
     return self.__qty 
    def set_qty (self, new_qty): 
     self.__qty = new_qty 
    def get_price (self): 
     return self.__price 
    def set_price (self, new_price): 
     self.__price = new_price 

    def calc_cost (self): 
     total = purch_qty * self.__price 

    def __str__ (self): 
     return self.__id + '\t' + self.__name + '\t' + \ 
     format (self.__qty, '7.2f') + format (self.__price, '7.2f') + \ 
     format (total, '7.2f') 

내 inventory.txt 파일입니다 :

import InventoryFile 
import os 

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]) 

     #create inventory object 
     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 modify(): 
    found = False 

    search = -1 
    while search == -1: 
     search = input ('Enter the ID of the product you would like to purchase: ') 

     try: 
      if search == '0': 
       print ('The inventory has been updated...') 
       break 

     except Exception: 
      search = -1 
      print ('ERROR: Please enter a valid number.') 

     else: 
      inventoryFile = open ('inventory.txt', 'r') 

      temp_file = open ('UpdatedInventory.txt', 'w') 

      ID = str (inventoryFile.readline()) 

      while ID != '': 
       item = str (inventoryFile.readline()) 
       qty = float (inventoryFile.readline()) 
       price = float (inventoryFile.readline()) 

       inventory_object = InventoryFile.Inventory (ID, item, qty, price) 

       ID = ID.rstrip ('\n') 

       if ID == search: 
        purchase = -1 
        while purchase == -1: 
         purchaseEntry = float (input ('How many would you like to purchase? Negative numbers are returns')) 
         purchase = inventory_object.purchase (purchaseEntry) 
         if purchase is False: 
          purchase = -1 
          print ('ERROR: Insufficient stock!') 

        new_qty = inventory_object.restock (purchase) 

        transaction_object = InventoryFile.TransactionItem (ID, item, new_qty, price) 

        transaction_object.set_id (ID) 
        transaction_object.set_name (item) 
        transaction_object.set_qty (new_qty) 
        transaction_object.set_price (price) 

        ID = transaction_object.get_id() 
        item = transaction_object.get_name() 
        qty = transaction_object.get_qty() 
        price = transaction_object.get_price() 

        temp_file.write (ID + '\n') 
        temp_file.write (item + '\n') 
        temp_file.write (str (qty) + '\n') 
        temp_file.write (str (price) + '\n') 

        found = True 

       else: 
        temp_file.write (ID + '\n') 
        temp_file.write (item + '\n') 
        temp_file.write (str (new_qty) + '\n') 
        temp_file.write (str (price) + '\n') 

       ID = inventoryFile.readline() 

      if found: 
       print ('The file has been updated.') 
      else: 
       print ('That item was not found in the file.') 

       inventoryFile.close() 
       temp_file.close() 

       os.remove ('inventory.txt') 

       os.rename ('UpdatedInventory.txt', 'inventory.txt') 

       print ('Inventory has been updated.') 
       break 

    return search 

def main(): 
    all_items = readFile() 
    printMenu (all_items) 
    modify() 


main() 

가 여기 내 재고 클래스 파일입니다 :

여기 내 주요 코드의 여기

244 
Large Cake Pan 
7 
19.99 
576 
Assorted Sprinkles 
3 
12.89 
212 
Deluxe Icing Set 
6 
37.97 
827 
Yellow Cake Mix 
3 
1.99 
194 
Cupcake Display Board 
2 
27.99 
285 
Bakery Boxes 
7 
8.59 
736 
Mixer 
5 
136.94 

그리고 것은 업데이트 된 것입니다 인벤토리 txt는 제품 ID 244를 입력하고 5의 구매 수량을 본 것처럼 보입니다.

244 
Large Cake Pan 

4.0 
19.99 
576 
Assorted Sprinkles 

4.0 
12.89 
212 
Deluxe Icing Set 

4.0 
37.97 
827 
Yellow Cake Mix 

4.0 
1.99 
194 
Cupcake Display Board 

4.0 
27.99 
285 
Bakery Boxes 

4.0 
8.59 
736 
Mixer 

4.0 
136.94 
+0

파이썬 코드를 작성하고 Python 구문으로 Java를 작성하지 않을 수도 있습니다 .-) 그 주요한 두 개의 밑줄과 사소한 getter 및 setter를 제거하십시오. 또한 예외적 인 일이있을 경우 반환 값을 사용하여 신호를 보내지 마십시오. 그게 예외가 사용되는 이유입니다. – BlackJack

답변

0

내가 장애인 TransactionItem을했습니다합니다. 이것은 작동하고있는 것 같습니다 (스크립트 파일을 결합했습니다) :

import os 


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 += new_stock 
      return True 

    def purchase(self, purch_qty): 
     if self.__stock >= purch_qty: 
      self.__stock -= purch_qty 
      return self.__stock 
     else: 
      print('ERROR: Insufficient stock') 
      return False 

    def __str__(self): 
     return self.__id + '\t' + self.__name + '\t' + \ 
      format(self.__stock, '7.2f') + format(self.__price, '7.2f') 


class TransactionItem (Inventory): 

    def __init__(self, new_id, new_name, new_qty, new_price): 
     self.__qty = new_qty 
     Inventory.__init__(self, new_id, new_name, new_qty, new_price) 

    def get_id(self): 
     return self.__id 

    def set_id(self, new_id): 
     self.__id = new_id 

    def get_name(self): 
     return self.__name 

    def set_name(self, new_name): 
     self.__name = new_name 

    def get_qty(self): 
     return self.__qty 

    def set_qty(self, new_qty): 
     self.__qty = new_qty 

    def get_price(self): 
     return self.__price 

    def set_price(self, new_price): 
     self.__price = new_price 

    def calc_cost(self): 
     self.total = purch_qty * self.__price 

    def __str__(self): 
     return self.__id + '\t' + self.__name + '\t' + \ 
      format (self.__qty, '7.2f') + format (self.__price, '7.2f') + \ 
      format(self.total, '7.2f') 


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]) 

     # create inventory object 
     inventory_object = 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 modify(): 
    found = False 

    search = -1 
    while search == -1: 
     search = input(
      'Enter the ID of the product you would like to purchase: ') 

     try: 
      if search == '0': 
       print('The inventory has been updated...') 
       break 

     except Exception: 
      search = -1 
      print('ERROR: Please enter a valid number.') 

     else: 
      inventoryFile = open('inventory.txt', 'r') 

      temp_file = open('UpdatedInventory.txt', 'w') 

      ID = str(inventoryFile.readline()) 

      while ID != '': 
       item = str(inventoryFile.readline()) 
       qty = float(inventoryFile.readline()) 
       price = float(inventoryFile.readline()) 

       inventory_object = Inventory(ID, item, qty, price) 

       ID = ID.rstrip('\n') 
       item = item.rstrip('\n') 

       if ID == search: 
        purchase = -1 
        while purchase == -1: 
         purchaseEntry = float(
          input('How many would you like to purchase? Negative numbers are returns')) 
         purchase = inventory_object.purchase(purchaseEntry) 
         if purchase is False: 
          purchase = -1 
          print('ERROR: Insufficient stock!') 

        #new_qty = inventory_object.restock(purchase) 

        #transaction_object = TransactionItem(
        # ID, item, new_qty, price) 

        #transaction_object.set_id(ID) 
        #transaction_object.set_name(item) 
        #transaction_object.set_qty(new_qty) 
        #transaction_object.set_price(price) 

        #ID = transaction_object.get_id() 
        #item = transaction_object.get_name() 
        #qty = transaction_object.get_qty() 
        #price = transaction_object.get_price() 

        qty = inventory_object.get_stock() 
        price = inventory_object.get_price() 

        temp_file.write(ID + '\n') 
        temp_file.write(item + '\n') 
        temp_file.write(str(int(qty)) + '\n') 
        temp_file.write(str(price) + '\n') 

        found = True 

       else: 
        temp_file.write(ID + '\n') 
        temp_file.write(item + '\n') 
        temp_file.write(str(int(qty)) + '\n') 
        temp_file.write(str(price) + '\n') 

       ID = inventoryFile.readline() 

      if found: 
       print('The file has been updated.') 
      else: 
       print('That item was not found in the file.') 

       inventoryFile.close() 
       temp_file.close() 

       os.remove('inventory.txt') 

       os.rename('UpdatedInventory.txt', 'inventory.txt') 

       print('Inventory has been updated.') 
       break 

    return search 


def main(): 
    all_items = readFile() 
    printMenu(all_items) 
    modify() 


main() 

나는 그것이 도움이되기를 바랍니다!

+0

빈 줄은 item에 float로 변환하기 때문에 마지막에 개행 문자와 부동 소수점이 있고 TransactionItem으로 계산 오류가 발생했습니다. 실제로 찾지 못했습니다. 무슨 일이 일어나고 있는지 추적하지 못하도록 단순화하고 주석을 달고 싶을 수도 있습니다. .. – handle

0

프로그램을 통해 스테핑을 시도 했습니까? 당신이 정보를 잃고있어 어떤 점에서 https://docs.python.org/2/library/pdb.html 또는

https://docs.python.org/3/library/pdb.html

(하드 코드의 큰 블록 슬프게도 문제를 해결하는)

+0

제안을 주셔서 감사합니다. 저는 파이썬에 대한 멍청한 행동입니다. 그래서 그 내용을 이해하는 방법을 이해하는 데는 시간이 걸리지 만 시도해 보겠습니다. –

관련 문제