0

Basically I am making an app to better assist me at managing my ebay store. I am still very new to programming and OOP. After watching some tutorials I pieced together the following code. Everything so far works pretty well. What I am currently stuck on is when the user inputs an item for inventory, it is not saving it. And, when the user wants to view the inventory the item they added wont populate. Any input or suggestions would be much apprenticed.

def Inventory():
    All_Inventory = {}

class Ebay_Inventory:

    def __init__(self, manufacturer, object_type, price):
        self.manufacturer = manufacturer
        self.object_type = object_type
        self.price = price

    def add_item(self):
        manufacturer = input("Enter Manufacturer: ")
        object_type = input("Enter what the item is: ")
        price = input("Enter price: ")

        item_info = Ebay_Inventory(manufacturer, object_type, price)
        All_Inventory = item_info
        print("Item added successfully")

    def delete_item(self):
        delete = input("What is the item you want to delete?: ")
        if delete in All_Inventory.keys():
            del[delete]
            print("The item entered has been deleted.")
        else:
            print("Item not found")


    def sale_status(self):
        update = input("What is the item you want to update?:")
        if update in All_Inventory.keys():
            pass
        else:
            print("Item not found")


user=True
while user:
    print("\n1. Add to item inventory")
    print("2. Remove item from inventory")
    print("3. Update sale status")
    print("4. View inventory")
    print("5. Exit program")
    user_wants=input("What would you like to do today?")
    if user_wants=="1":
        Ebay_Inventory.add_item(input)
    elif user_wants=="2":
        Ebay_Inventory.delete_item(input)
    elif user_wants=="3":
        Ebay_Inventory.sale_status(input)
    elif user_wants=="4":
        print(All_Inventory)
    elif user_wants=="5":
        print("\n Thank you for using item inventory.")
        break
    elif user_wants!="":
        print("\n Input not understood. Please try again.")
  • You define `Inventory` and `all_inventory` in a function outside the class, but the function's only purpose is to declare a local empty set. Then you recursively create a new ebay_inventory object each time you try to add an item. This looks like an odd mashup of functional and object oriented programming – G. Anderson Feb 26 '19 at 21:50

2 Answers2

0

You need to read about Scope, OOP and dicts:

You are not adding to your Inventory.All_Inventory - you create a new local with All_Inventory = item_info

You mix up static class attributes and instance attributes, read:

You are deleting / accessing your dictionary wrongly - see :

Fixed:

class Ebay_Inventory:
    Inventory = {}                                    # class property


    @staticmethod
    def print_inventory():
        for k in Ebay_Inventory.Inventory:
            for i in Ebay_Inventory.Inventory[k]:
                print(k,i)

    class Ebay_Item:
        def __init__(self, key, manufacturer, object_type, price):
            self.manufacturer = manufacturer
            self.object_type = object_type
            self.price = price 
            self.key = key

        def __str__(self):
            return f"{self.manufacturer} {self.object_type} {self.price}"

        def __repr__(self):
            return str(self)

    @staticmethod    
    def add_item(key=None, man=None, obj=None, pri=None):
        # use values if given, else ask - this is for demo purposes only
        key = key or input("Enter key: ")
        manufacturer = man or input("Enter Manufacturer: ")
        object_type = obj or input("Enter what the item is: ")
        price = pri or input("Enter price: ")

        # create new item   
        item_info = Ebay_Inventory.Ebay_Item(key, manufacturer, object_type, price)

        # add to class member, create key if need be
        Ebay_Inventory.Inventory.setdefault(item_info.key,[]).append(item_info)

    def delete_item(key=None):
        delete = key or input("What is the item you want to delete?: ")
        if delete in Ebay_Inventory.Inventory:
            del Ebay_Inventory.Inventory[delete]
            print("The item entered has been deleted.")
        else:
            print("Item not found")

    def __str__(self):
        return Ebay_Inventory.print_inventory()

# add 2 items and print
Ebay_Inventory.add_item(1,"Me","Me",1000)
Ebay_Inventory.add_item(2,"You","You",1000)
Ebay_Inventory.print_inventory()

# remove non existent and existent item and print
Ebay_Inventory.delete_item(3)
Ebay_Inventory.delete_item(2)
Ebay_Inventory.print_inventory()

Output:

1 Me Me 1000
2 You You 1000
Item not found
The item entered has been deleted.
1 Me Me 1000
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

Sorry to rework your code pretty extensively, but I think this is more like what you are going for:

class EbayInventory:
    def __init__(self):
        self.all_inventory = []

    def print_items(self):
        print('Current item list by index:')
        for i in range(0, len(self.all_inventory)):
            print("{} -> {}".format(i+1, self.all_inventory[i]))

    def add_item(self):
        manufacturer = input("Enter Manufacturer: ")
        object_type = input("Enter what the item is: ")
        price = input("Enter price: ")
        item = {'manufacturer': manufacturer, 'type': object_type, 'price': price}
        self.all_inventory.append(item)
        print("Item added successfully")

    def delete_item(self):
        self.print_items()
        delete = int(input("Item id you want to delete: "))
        try:
            del self.all_inventory[delete - 1]
            print("The item entered has been deleted.")
        except Exception as e:
            print("An error occurred deleting that item, details below")
            print(e)

    def sale_status(self):
        self.print_items()
        update_index = int(input("Item id you want to update: "))
        if update_index > len(self.all_inventory) or update_index <= 0:
            print("You're trying to change an item that doesn't exist!!")
            return
        print("OK. Let's get that item up to date!")
        manufacturer = input("Enter Manufacturer: ")
        object_type = input("Enter what the item is: ")
        price = input("Enter price: ")
        item = {'manufacturer': manufacturer, 'type': object_type, 'price': price}
        self.all_inventory[update_index - 1] = item
        print("OK. We got that update taken care of")

if __name__ == "__main__":
    my_app = EbayInventory()
    while True:
        print("\n1. Add to item inventory")
        print("2. Remove item from inventory")
        print("3. Update sale status")
        print("4. View inventory")
        print("5. Exit program")
        user_wants = input("Please enter the number corresponding to how you would like help: ")
        if user_wants == "1":
            my_app.add_item()
        elif user_wants == "2":
            my_app.delete_item()
        elif user_wants == "3":
            my_app.sale_status()
        elif user_wants == "4":
            my_app.print_items()
        elif user_wants == "5":
            print("Thank you for using item inventory.")
            break
        else:
            print("Input not understood. Please try again.")

You had a variable user that did nothing. You can simply enter an infinite loop with while True:. If you wanted to loop the way you did, then instead of a break you could have put a user = False to break out of the loop. This is sometimes a nifty trick, but doesn't make sense here I think. It seemed to me the inventory was really the only thing that would benefit by being stored in your class, and the methods could then access it to adjust it via a self.all_inventory. I moved your code to ask for item inputs to the add_item() and sale_status() methods, so now the main block of code looks a lot cleaner. I also wrapped it in if __name__ == "__main__": so that you can import this class to another project without running the entire program! I threw in some basic error checking with try: and except: clauses also. I think you were misunderstanding the difference between a Class and an Instance. So in my code the Class is EbayInventory, but the Instance is my_app. You create instances of your class just like I did with my_app = EbayInventory() and then the self now refers to my_app. In this manner I can call my_app.add_item(). You can have several instances of objects though, and they each have their own space in your computers memory. So you could have said:

app1 = EbayInventory()
app2 = EbayInventory()
app1.add_item()

And only the app1 will have any items, whereas app2 is still an empty list, but still has the methods to build an inventory via app2.add_item(). To answer your main question though, you never call your function Inventory() and therefore it doesn't exist to hold your information. When you call item_info = Ebay_Inventory(manufacturer, object_type, price) in fact you are making an Instance of a class, which is really nonsensical to do here because that means on the next line you could say item_info.add_item() and this would make another instance, yet you are not saving this information anywhere so you can never retrieve it!

Reedinationer
  • 5,661
  • 1
  • 12
  • 33