2016-11-22 6 views
0

それぞれにオブジェクトを含む複数のリストがあります。すべてのオブジェクトの値は「名前」と「金額」です。私がしたいのは、まずユーザー入力(名前を見つけるために名前を入力)でリスト内の項目を見つけてから、ユーザー入力値を加算または減算することによって「金額」を更新する方法を作成することです(減算する値を追加/ )。リスト内のオブジェクトの値を更新する

どうすればいいですか?

これは私が(それは不完全だが、それは私が成し遂げることができるすべてです)これまで持っているものです。

Containers = [] 
Lids = [] 
Wicks = [] 
Labels = [] 
Misc = [] 

    class item(object): 

     #Constructor 
     def __init__(self, name, amount): 
      self.name = name 
      self.amount = amount 

     #Accessors 
     def getName(self): 
      return self.name 

     def getAmount(self): 
      return self.amount 


     #Mutators 
     def __str__(self): 
      return "[Name: " + self.name + \ 
        ", Amount: " + self.amount + \ 
        "]" 

     def addAmount(): 
      found = False 
      name = input("Enter the name of a container you wish to change: ") 
      addNewAmount = input("Enter the amount you wish to add: ") 
      for item in Containers: 
       if name in item.getName(): 
        found = True 
        position = Containers.index(name) 
        print(Containers[position]) 
      if not found: 
       print("No names match that input.") 

     def subtractAmount(): 
      update = input("Enter a new amount to subtract: ") 
      self.amount = amount - update 

     def addContainer(): 
      name = input("Enter a name for the new container: ") 
      amount = input("Enter an amount for the new container: ") 
      return item(name, amount) 

     def addLid(): 
      name = input("Enter a name for the new lid: ") 
      amount = input("Enter an amount for the new lid: ") 
      return item(name, amount) 

     def addWick(): 
      name = input("Enter a name for the new wick: ") 
      amount = input("Enter an amount for the new wick: ") 
      return item(name, amount) 

     def addLabel(): 
      name = input("Enter a name for the new label: ") 
      amount = input("Enter an amount for the new label: ") 
      return item(name, amount) 

     def addMisc(): 
      name = input("Enter a name for the new misc item: ") 
      amount = input("Enter an amount for the new misc item: ") 
      return item(name, amount) 

     def main(): 
      running = True 
      while running: 
       print("Enter a number to start.") 
       print("1) Add new container   2) Add new lid") 
       print("3) Add new wick    4) Add new label") 
       print("5) Add new misc Item   6) Print Inventory") 
       print("7) Add Amount from item  8) Subtract Amount from item") 
       print("10) quit") 
       print("11) print list") 
       choice = input("> ") 
       if choice == "1": 
        Containers.append(addContainer()) 
       elif choice == "2": 
        Lids.append(addLid()) 
       elif choice == "3": 
        Wicks.append(addWick()) 
       elif choice == "4": 
        Labels.append(addLabel()) 
       elif choice == "5": 
        Misc.append(addMisc()) 
       elif choice == "6": 
        print("<==========Containers==========>") 
        for i in Containers: 
         print(i) 
        print("<=============Lids=============>") 
        for i in Lids: 
         print(i) 
        print("<=============Wicks============>") 
        for i in Wicks: 
         print(i) 
        print("<============Labels============>") 
        for i in Labels: 
         print(i) 
        print("<==========Misc Items==========>") 
        for i in Misc: 
         print(i) 
       elif choice == "7": 
        return addAmount() 
       elif choice == "8": 
        return subtractAmount() 
       elif choice == "10": 
        quit() 
       elif choice == "11": 
        print('[%s]' % ', '.join(map(str, Containers))) 
       else: 
        print("Invalid entry, please try again.") 

     if __name__ == "__main__": 
      main() 

答えて

0

ここにいくつかの問題があります。最初は、コンテナ、蓋、ウィックなどをすべて同じタイプのオブジェクト(「アイテム」)にするか、サブクラスを持つのがより合理的かどうかです。それらをすべて同じ(「アイテム」)にしたいと思っている場合は、以下のコードに従ってメソッドを調整することができます(単純化のために多くのオプションがありません)。

カップルの注意すべき点:

  • 正しくからアイテムの作成を加算または減算するために、数値にする必要がある

    1. 「量」(int)がクラスの外側の関数です、
    2. "add_amount"関数は、すべてのアイテムのすべてのリストを調べて、一致する可能性のあるアイテムを見つけ、それに応じて量を調整します。リッドとコンテナの名前が同じ場合、最初のマッチが変更されます。

      Containers = [] 
      Lids = [] 
      Items = [Containers, Lids] 
      
      class item(object): 
      
          #Constructor 
          def __init__(self, name, amount): 
           self.name = name 
           self.amount = amount 
      
          #Accessors 
          def getName(self): 
           return self.name 
      
          def getAmount(self): 
           return self.amount 
      
          def __str__(self): 
           return "[Name: " + self.name + \ 
            ", Amount: " + str(self.amount) + \ 
            "]" 
      
      def addItem(): 
          global new_item 
          name = input("Enter a name for the new item: ") 
          amount = int(input("Enter an amount for the new item: ")) 
          new_item = item(name, amount) 
          return new_item 
      
      
      def add_amount(): 
          found = False 
          name = input("Enter the name of the item you wish to change: ") 
          add_amount = int(input("Enter the amount you wish to add: ")) 
          for itemList in Items: 
           for item in itemList: 
            if name == item.getName(): 
             found = True 
             position = itemList.index(item) 
             item.amount += add_amount 
             print(itemList[position]) 
            if not found: 
             print("No names in match that input.") 
      
      def main(): 
          running = True 
          while running: 
           print("Enter a number to start.") 
           print("1) Make a container   2) Make a lid") 
           print("3) add amount    4) quit") 
           choice = input("> ") 
           if choice == "1": 
            addItem() 
            print new_item.amount 
            Containers.append(new_item)    
           elif choice == "2": 
            addItem() 
            print new_item.amount 
            Lids.append(new_item) 
           elif choice == "3": 
            add_amount()   
           elif choice == "4": 
            quit() 
           else: 
            print("Invalid entry, please try again.") 
      
      if __name__ == "__main__": 
          main() 
      
  • +0

    [OK]を、私はこのコードをしようとしているし、今私はエラーにこだわっている:「はAttributeError: 『タプル』オブジェクトが属性 『金額』を持っていない、なぜこれが起こっているわからないことがあります。 print(new_item.amount)の83行目で起こっています グローバル変数new_itemに変数として量が確実に追加されます そして、下のコードの各選択肢からすべてのprint(new_item.amount)行を削除した場合"TypeError: 'tuple'オブジェクトが呼び出し可能でないことを示すContainers.append(new_item)でエラーが発生する また、addAmount()メソッドはまだ変更されていません。その位置の値。 – cstmxyz

    +0

    私はそれを働かせました。最後にはそこにいてはならない方法で何かを呼び出すと、それは私にエラーを与えていました。あなたのすべての協力に感謝します!私はファイルを持っていて、リストを外部ファイルにエクスポートして保存し、プログラムをロードするときにそれらをロードすることさえできました! – cstmxyz

    0

    これは一種の厄介かもしれませんが、仕事をする必要があります。

    def subtractAmount(): 
         containers = [Containers, Lids, Wicks, Labels, Misc] 
         names = ['Containers', 'Lids', 'Wicks', 'Labels', 'Misc'] 
         print('Select the number of list you want to search for item') 
         print('\n'.join('{}) {}'.format(str(idx), lst_name) for (idx, lst_name) in enumerate(names, 1))) 
         selected = input(': ')) - 1 
         item_name = input('Enter the item name you are looking for: ') 
         item = None 
         for value in containers[selected]: 
         if value.getName().lower() == item_name.lower(): 
         item = value 
         break 
         else: 
          print('No item was found with that name!') 
         new_amount = input('Enter the new amount for item: ') 
         item.amount = new_amount 
    
    関連する問題