首页 > 解决方案 > 从用户输入中正确使用类和字典

问题描述

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

我应该只使用 list 还是我认为这是正确的方式,将值存储在字典或某种嵌套的 dict 中。

我特别不知所措,menu==3 #delete an item因为现在我只能删除一个属性,但我需要的是尽可能按属性 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()

标签: pythonpython-3.x

解决方案


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

如果您想保存属性并能够再次加载它们,请将此方法添加到Property

class Property:

    ...

    @classmethod
    def from_json(cls, json_code):
        c = cls(*(None for _ in range(8)))

        for x,y in json_code.items():
            setattr(c, x, y)

        return c

并将此功能添加到您的程序主体中:

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


推荐阅读