Home > Net >  How to Call/Run Specific Methods within my Main Loop?
How to Call/Run Specific Methods within my Main Loop?

Time:09-19

I am currently in the process of making an inventory system, and am working on my main loop. Currently I am trying to make it in the main loop, that when a user inputs 1, it sends them through the process of adding a new item.

I have the following relevant code:

import csv
class user_interaction(object):

    def __init__(self):
        self.name = self.ask()
        self.options = self.ask_options()
        self.database = DataBase_Management()
        
    def ask(self):
        while True:
            name = input("What is your name?\n")
            if name == "":
                print("Ha! You have to enter a name!")
            else:
                print("Welcome to the Shepherdstown Bake Shop "   name)
                return name
            
        
                
    def ask_options(self):
        while True:
            option = input('''What would you like to do? \n1. Add a Item: \n2. Delete a Item:\n3. Edit an Item: \n4. View Inventory \n5. End Program\n''')
            if option == '1':       
                print("Welcome to the adding process "   self.name)
                items = DataBase_Management()
                items.make_dict_items()
                self.add_item_interaction()
                #add_item_interaction()
                #items.add_item()
                break

   def enter_data(selfmessage, typ):
            while True:
                try:
                    v = typ(input(message))
                except ValueError:
                    print(f"Thats not an {typ}!")
                    continue
                else:
                    break
            return v

     def add_item_interaction(self):
            add_item_num = enter_data("What is the items #?\n", int)
            add_item_price = enter_data("What is the items price?\n", float)
            add_item_quant = enter_data("What is the items quantity?\n", int)

            while True:
                add_name = self.enter_data("What is the items name?\n", str)
                if name == "":
                    print("Ha! You have to enter a name!")
                    continue
                break
            self.database.add_item(add_item_num, add_item_price, add_item_quant, add_name)

as well as the other class:

class DataBase_Management(object):
    
    def __init__(self):
        self.result = []


    def make_dict_items(self):
        with open("Items2.csv") as fp:
            reader = csv.reader(fp)
            labels = next(reader, None)
            result = []
            for row in reader:
                if row:
                    row[0] = int(row[0])
                    row[1] = float(row[1])
                    row[2] = int(row[2])
                    pairs = zip(labels, row)
                    self.result.append(dict(pairs))


    def add_item(self, item_num, price, quant, name):
        new_row = [item_num, price, quant, name]
        with open("Items2.csv", "a ") as  fp:
           reader = csv.reader(fp)
           fp.seek(0)
           labels = next(reader, None)
           writer = csv.writer(fp)
           new_record = dict(zip(labels, new_row))
           self.result.append(new_record)
           writer.writerow(new_record.values())
           print("Item Added! Check Inventory Again to see!")


if __name__ == "__main__":
    obj = user_interaction() 
    while True:
        obj.ask_options() 

I was wondering how I can implement it into my ask_options main loop, that if a user inputs 1, it sends them to add_item_interaction and enter_data in the first class, and then adds the new items to the database as is done by add_item in the second class? The comments in the ask_options method were my attempts/thoughts at doing so.

EDIT: Added some suggested code, and seem to now get error:

Traceback (most recent call last):
  
 line 209, in <module>
    obj = user_interaction()
  
line 7, in __init__
    self.options = self.ask_options()
  
 
line 28, in ask_options
    self.add_item_interaction()

AttributeError: 'user_interaction' object has no attribute 'add_item_interaction'

CodePudding user response:

This code should be the next step forward:

import csv
class User_Interaction:

    def __init__(self, name):
        self.name = name
        self.database = DataBase_Management()
        self.database.make_dict_items()
    
    @staticmethod
    def ask():
        while True:
            name = input("What is your name?\n")
            if name == "":
                print("Ha! You have to enter a name!")
            else:
                print("Welcome to the Shepherdstown Bake Shop "   name)
                return name
                
    def ask_options(self):
        option = input('''What would you like to do? \n1. Add a Item: \n2. Delete a Item:\n3. Edit an Item: \n4. View Inventory \n5. End Program\n''')
        if option == '1':       
            print("Welcome to the adding process "   self.name)
            self.add_item_interaction()
        elif option == '2':
            ...

    @staticmethod
    def enter_data(message, typ):
            while True:
                try:
                    v = typ(input(message))
                except ValueError:
                    print(f"Thats not an {typ}!")
                    continue
                else:
                    break
            return v

     def add_item_interaction(self):
            add_item_num = self.enter_data("What is the items #?\n", int)
            add_item_price = self.enter_data("What is the items price?\n", float)
            add_item_quant = self.enter_data("What is the items quantity?\n", int)

            while True:
                add_name = self.enter_data("What is the items name?\n", str)
                if add_name == "":
                    print("Ha! You have to enter a name!")
                    continue
                break
            self.database.add_item(add_item_num, add_item_price, add_item_quant, add_name)

Note the changes to the __init__() method and how some other methods are marked @staticmethod since those never need access to self.

Also ask_options() doesn't need its own while loop since that is already included below.

Also I've added an elif/... in ask_options() as a placeholder for all the other options that need implementing and is not real code.

class DataBase_Management:
    def __init__(self):
        self.result = []

    def make_dict_items(self):
        with open("Items2.csv") as fp:
            reader = csv.reader(fp)
            labels = next(reader, None)
            result = []
            for row in reader:
                if row:
                    row[0] = int(row[0])
                    row[1] = float(row[1])
                    row[2] = int(row[2])
                    pairs = zip(labels, row)
                    self.result.append(dict(pairs))

    def add_item(self, item_num, price, quant, name):
        new_row = [item_num, price, quant, name]
        with open("Items2.csv", "a ") as  fp:
           reader = csv.reader(fp)
           fp.seek(0)
           labels = next(reader, None)
           writer = csv.writer(fp)
           new_record = dict(zip(labels, new_row))
           self.result.append(new_record)
           writer.writerow(new_record.values())
           print("Item Added! Check Inventory Again to see!")

if __name__ == "__main__":
    name = User_Interaction.ask()
    obj = User_Interaction(name) 
    while True:
        obj.ask_options()

Note that some variables can just be local to methods and don't need to be members. (eg. You don't need self.add_item_name)

Note that the __init__() method only really initialises members that it needs control over. (Yes, it is debateable whether ask() should be called outside as I have done or whether it should be called inside as you did)

Note that there are some formatting issues with your posted code. You should be using an IDE that would immediately highlight such things so that we never see them in code posted here.

Note that classes can be declared: class Foo: (No brackets nor the need to derive from object)

Also note that, as I've said previously, you should not use stackoverflow and your personal software development environment. You are asking questions and stitching together a program from the answers in a cargo cult style that will lead to much confusion and less than optimal learning.

  • Related