【问题标题】:name 'item' is not defined名称“项目”未定义
【发布时间】:2020-02-18 16:19:04
【问题描述】:

我把曾经的课堂项目变成了更适合工作的东西。我的程序被设计成一个库存系统。我目前已确保我的程序可以将数据导出到文本文件,并在程序关闭时根据请求导入该数据。导入后我无法编辑数据,除非我先将新数据添加到列表中,或者将新数据添加到列表中然后导入。

我认为它不起作用的原因是因为从列表中导入的数据在添加新数据之前还没有逻辑位置。

class Inventory: 
    def __init__(self):
        self.item = ""
        self.amount = 0
        self.asset_tag = 0
        self.notes = ""

    def add_inventory(self):
        self.item = input("Enter item: ")
        self.amount = int(input("How many? "))
        self.asset_tag = int(input("Enter Asset Tag if available. Enter 0 if not tagged. "))
        self.notes = input("Please add any additional information: ")
    def __str__(self):
        return('Item: %s Amount: %d Asset Tag: %d Notes: %s' %
               (self.item, self.amount, self.asset_tag, self.notes))

inventory_list = []

def edit(inventory_list):
    pos = int(input('Enter the position of the item you would like to edit: '))
    new_inventory = item.add_inventory()
    new_inventory = item.__str__()
    inventory_list[pos-1] = new_inventory
    print('Inventory has been updated. If the amount is now 0 please notify.')

while True:
    print("""
    1. Add new inventory.
    2. Remove item from inventory.
    3. View inventory.
    4. Update current inventory.
    5. Export inventory to file.
    6. Import Inventory file 
    7. Quit
    """)
    ans = input('What would you like to do? ')
    if ans == "1":
        item = Inventory()
        item.add_inventory()
        inventory_list.append(item.__str__())
    elif ans == "2":
        for i in inventory_list:
            inventory_list.pop(int(input('Enter position of item to remove: ')))
            print('Inventory item removed successfully!')        
    elif ans == "3":
        print('\n'.join(map(str, inventory_list)))
    elif ans == "4":
        edit(inventory_list)
    elif ans == "5":
        f = open('Inventory_List.txt', 'w')
        for ele in inventory_list:
            f.write(ele+'\n')
        f.close()
    elif ans == "6":
        with open('Inventory_List.txt') as f:
            data = f.read().splitlines()
            print(data)
            inventory_list.extend(data)
    elif ans == "7":
        break
    else:
        print('Invalid entry, try again.')``` 


【问题讨论】:

  • 请编辑您的问题以包含您认为自己拥有的想法
  • 请将您的问题简化为一个最小示例 - stackoverflow.com/help/minimal-reproducible-example
  • item 未在您的 edit 函数中的任何位置定义。你的意思是editinventory 的成员函数吗?
  • 我猜你错过了类似item = inventory_list[pos]

标签: python inventory


【解决方案1】:

item 在被使用之前没有在函数编辑中定义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    相关资源
    最近更新 更多