用户输入未保存到库存清单

时间:2019-02-26 21:27:02

标签: python oop inventory

基本上,我正在制作一个应用程序,以更好地帮助我管理自己的eBay商店。我对编程和OOP还是很陌生。看了一些教程之后,我整理了以下代码。到目前为止,一切工作正常。我目前坚持的是,当用户输入要库存的物料时,它没有保存。而且,当用户想要查看库存时,他们添加的项目将不会填充。任何意见或建议都将是徒劳的。

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.")

2 个答案:

答案 0 :(得分:0)

您需要阅读有关范围,OOP和字典的信息:

您没有添加到Inventory.All_Inventory中-您使用All_Inventory = item_info创建了新的本地

您将静态类属性和实例属性混合在一起,请阅读:

您错误地删除/访问字典-请参阅:

已修复:

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

输出:

1 Me Me 1000
2 You You 1000
Item not found
The item entered has been deleted.
1 Me Me 1000

答案 1 :(得分:0)

很抱歉,您需要对代码进行大量修改,但是我认为这更像您要使用的代码:

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.")

您有一个变量user,它没有任何作用。您可以简单地使用while True:输入无限循环。如果您想按自己的方式循环,那么可以用break代替循环user = False来代替循环。有时这是一个很巧妙的技巧,但我认为在这里没有意义。在我看来,清单确实是唯一可以通过存储在您的类中而受益的东西,然后这些方法可以通过self.all_inventory对其进行访问以对其进行调整。我将您的代码移到了add_item()sale_status()方法中,要求输入项目,因此现在主要的代码块看起来更加整洁。我还将其包装在if __name__ == "__main__":中,以便您可以将此类导入另一个项目,而无需运行整个程序!我还使用try:except:子句进行了一些基本的错误检查。我认为您误解了ClassInstance之间的区别。因此,在我的代码中,Class是EbayInventory,而Instancemy_app。您可以像使用my_app = EbayInventory()一样创建类的实例,然后自身现在引用my_app。通过这种方式,我可以打电话给my_app.add_item()。但是,您可以有多个对象实例,并且它们在计算机内存中都有各自的空间。所以你可能会说:

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

并且只有app1将具有任何项目,而app2仍然是一个空列表,但仍具有methods可以通过app2.add_item()建立库存。但是,要回答您的主要问题,请不要调用函数Inventory(),因此不存在用于保存信息的函数。实际上,当您调用item_info = Ebay_Inventory(manufacturer, object_type, price)时,您是在创建类的实例,在这里这样做实在是没有意义的,因为这意味着在下一行您可以说item_info.add_item(),而这会成为另一个实例,但您并未将这些信息保存在任何地方,因此您将永远无法获取它!