Python 正确使用用户输入的类和dict

Python 正确使用用户输入的类和dict,python,python-3.x,Python,Python 3.x,我一直在为一个班级项目的代码而挣扎,需要一些帮助。我不确定我是否需要一个嵌套字典或dict列表,或者只是在列表或dict中使用class。我一直在努力寻找答案,可能需要一些代码方面的帮助 我是应该使用list,还是应该用正确的方法,将值存储在字典或某种嵌套dict中 对于menu==3删除一个项目,我尤其感到困惑,因为现在我只能删除一个属性,但如果可能的话,我需要的是按属性ID删除整个属性 正如您可能知道的,我现在很困惑,非常感谢经验丰富的程序员提供的任何帮助 inventory = {} #

我一直在为一个班级项目的代码而挣扎,需要一些帮助。我不确定我是否需要一个嵌套字典或dict列表,或者只是在列表或dict中使用class。我一直在努力寻找答案,可能需要一些代码方面的帮助

我是应该使用list,还是应该用正确的方法,将值存储在字典或某种嵌套dict中

对于menu==3删除一个项目,我尤其感到困惑,因为现在我只能删除一个属性,但如果可能的话,我需要的是按属性ID删除整个属性

正如您可能知道的,我现在很困惑,非常感谢经验丰富的程序员提供的任何帮助

inventory = {}

#class & constructor
class Property:  
    def __init__(self, propertyID, address, city, state, zipcode, squarefeet, modelname, salestatus):
        self.propertyID = propertyID
        self.address = address
        self.city = city
        self.state = state
        self.zipcode = zipcode
        self.modelname = modelname
        self.squarefeet = squarefeet + 'Square Feet'
        self.salestatus = salestatus


def print_Property(o):
    if not isinstance(o, Property):
        raise TypeError('print_Property(): requires a Property')
    print('The property selected is Property ID: {} located at {} {} {} The Sqare footage is {}, {} model, Current status: {}'. format(o.propertyID,o.addresss, o.city, o.state, o.zipcode, o.squarefeet, o.modelname, o.salestatus))  

def main():
    print('What would you like to do today?')
    print('----------------------------------------')
    print('1. Add a new item to the Inventory')
    print('2. Update an Existing item in the Inventory')
    print('3. Delete an existing item from the Inventory')
    print('4. View the current item inventory')
    print('5. Print the Inventory to a text file')
    print('------------------------------')
    while True:
        try:
            menu = int(input('Type a number 1-5'))    

            if menu == 1: #Add data
              print('Add a new property to the inventory...')

              propertyID = input('Enter the property Listing ID:') #User inputting a property ID
              inventory['Property ID']= propertyID

              address = input('Enter the property address:') #User inputting an address
              inventory['Address']= address

              city = input('Enter property city:') #User inputting a city
              inventory['City']= city

              state = input('Enter property state:') #User inputting a state
              inventory['State']= state

              zipcode = int(input('Enter the property zipcode:')) #User inputting a zipcode
              inventory['Zipcode']= zipcode

              modelname = input('Enter property model name:') #User inputting a property model name
              inventory['Model Name']= modelname

              squarefeet = int(input('Enter the sqaure footage of the property:')) #User inputting the sqaure footage for the property
              inventory['Square Footage']= squarefeet

              salestatus = input('Enter the property status:(Is the home sold, available, or under contract?):') #User inputting the property status
              inventory['Current Staus']= salestatus


              print('The following properties are in the inventory now:')
              print(inventory)
              #break

            elif menu == 2: #Update data
              print('Update an item from the inventory...')

              print (inventory)

              itemreplace = input("Enter the name of the attribute you wish to replace:")
              itemupdate = input("Enter the new information for that attribute now:")
              inventory[itemreplace]= itemupdate

              print(inventory)

            elif menu == 3: #Delete data
              print("Which property do you want to delete?")
              print(inventory)

              itemdel = input("Enter the Property ID of the property to delete.")
              if itemdel in inventory:
                del inventory[itemdel]

              print(inventory)

            elif menu == 4: #View data
              print(inventory)

            elif menu == 5: #Print data
              output = open("PropertyData.txt", "w")
              for item in inventory:
                output.write("%s\n" % item)
              print('Text file \'PropertyData.txt\' has been created.')

            else:
              print('That number is not valid. Please try 1-5.')

        except ValueError: #throw an error for anything that is not a number
              print('You may only select values 1-5. (ex.: 2)')

if __name__ == '__main__': main()

最简单的解决方案是使用属性对象列表,其中列表中的每个元素都是一个单独的属性。将属性添加到资源清册意味着创建一个新对象,填充所有字段并将其附加到资源清册列表中。

@Lucas是正确的。我认为这是一个完全有效的系统:

import json

class Property:  
    def __init__(self, propertyID, address, city, state, zipcode, squarefeet, modelname, salestatus):
        self.propertyID = propertyID
        self.address = address
        self.city = city
        self.state = state
        self.zipcode = zipcode
        self.modelname = modelname
        self.squarefeet = squarefeet
        self._sqfeet_description = str(squarefeet) + ' Square Feet'
        self.salestatus = salestatus

    def __str__(self):
        o = self
        return 'Property ID: {}. Address: {}, {}, {}, {}. Size: {} sq feet, {} model. Status: {}.'.format(o.propertyID,o.address, o.city, o.state, o.zipcode, o.squarefeet, o.modelname, o.salestatus)

    def as_json(self):
        return {x:y for x,y in self.__dict__.items() if not x.startswith("_")}

def int_input(prompt, range=None):
    while True:
        ans = input(prompt)
        if not ans.isnumeric():
            print("Please enter a valid number")
            continue

        ans = int(ans)
        if range == None:
            return ans

        if ans not in range:
            print(f"Please enter a number between {min(range)} and {max(range)}")
            continue

        return ans

inventory = []

def main():
    print('What would you like to do today?')
    print('----------------------------------------')
    print('1. Add a new item to the Inventory')
    print('2. Update an Existing item in the Inventory')
    print('3. Delete an existing item from the Inventory')
    print('4. View the current item inventory')
    print('5. Print the Inventory to a text file')
    print('------------------------------')
    while True:
        menu = int_input("Choose an option 1-5", range(1,6))
        if menu == 1:
            # add data
            propertyID = input('Enter the property Listing ID:') #User inputting a property ID
            address = input('Enter the property address:') #User inputting an address
            city = input('Enter property city:') #User inputting a city
            state = input('Enter property state:') #User inputting a state
            zipcode = int_input('Enter the property zipcode:') #User inputting a zipcode
            modelname = input('Enter property model name:') #User inputting a property model name
            squarefeet = int_input('Enter the sqaure footage of the property:') #User inputting the sqaure footage for the property
            salestatus = input('Enter the property status:(Is the home sold, available, or under contract?):') #User inputting the property status

            this_property = Property(
                propertyID,
                address,
                city,
                state,
                zipcode,
                squarefeet,
                modelname,
                salestatus)

            inventory.append(this_property)

            print('The following properties are in the inventory now:')
            print(*("\t" + str(i) for i in inventory), sep="\n")
            print()
        elif menu == 2:
            # update data
            while True:
                propertyID = input("Enter the property id: ")
                this_property = [x for x in inventory if x.propertyID == propertyID]
                if not this_property:
                    print("That property doesn't exist")
                    continue
                this_property = this_property[0]
                break

            lookup = {
                "propertyID": str,
                "address":str,
                "city":str,
                "state":str,
                "zipcode":int,
                "modelname":str,
                "squarefeet":int,
                "salestatus":str
            }

            while True:
                detail_name = input("Enter the detail you wish to change")
                if detail_name not in lookup:
                    print("That detail does not exist")
                    continue
                break

            if lookup[detail_name] == int:
                new = int_input("Enter the new value:")
            else:
                new = input("Enter the new value:")

            setattr(this_property, detail_name, new)
        elif menu == 3:
            # delete
            while True:
                propertyID = input("Enter the property id: ")
                this_property = [i for i, x in enumerate(inventory) if x.propertyID == propertyID]
                if not this_property:
                    print("That property doesn't exist")
                    continue
                this_property = this_property[0]
                break

            del inventory[this_property]
        elif menu == 4:
            # print inventory
            print('The following properties are in the inventory now:')
            print(*("\t" + str(i) for i in inventory), sep="\n")
            print()

        elif menu == 5:
            # save
            new_inv = [x.as_json() for x in inventory]
            with open("output.txt", "w") as f:
                json.dump(new_inv, f)

if __name__ == '__main__':
    main()
如果要保存属性并能够再次加载它们,请将此方法添加到属性:

将此函数添加到程序体:

def load_from_file():
    with open("output.txt") as f:
        for item in json.load(f):
            inventory.append(Property.from_json(item))
然后在开始时调用该函数:

if __name__ == '__main__':
    load_from_file()
    main()

显然,请确保该文件在此之前存在-在第一次运行程序之前,只需将[]保存到output.txt即可

谢谢!那真的帮了汉克斯很大的忙!以功能形式查看代码确实让我更容易理解我在哪里犯了错误。感谢您花时间回复@JorinBecker很高兴能提供帮助:如果这有用,请投票并接受:
if __name__ == '__main__':
    load_from_file()
    main()