简体   繁体   English

存储用户输入数据以供稍后在 Python 中调用的方法?

[英]Way to store user input data to be called later in Python?

New to Python and am working on a task my friend gave me. Python 新手,正在处理我朋友给我的任务。 The objective for this portion is to find user information that was previously added to a dictionary.此部分的目标是查找先前添加到字典中的用户信息。 I am trying to find a way that if the user is searching for a particular user, only that user's info will be returned.我试图找到一种方法,如果用户正在搜索特定用户,则只会返回该用户的信息。 So far this is the code I have for this portion of the project:到目前为止,这是我为该项目的这一部分编写的代码:

selection = input('Please select an option 1 - 4:\t')

if selection == '1':

    print('Add user - Enter the information for the new user:\t')
    first_name = input('First name:\t')
    last_name = input('Last name:\t')
    hair_color = input('Hair color:\t')
    eye_color = input('Eye color:\t')
    age = input('Age:\t')

    user_info = {}
    user_info['First name'] = first_name
    user_info['Last name'] = last_name
    user_info['Hair color'] = hair_color
    user_info['Eye color'] = eye_color
    user_info['Age'] = age

Skipping code for sake of space on post为了帖子的空间而跳过代码

if selection == '3':
    print('\nChoose how to look up a user')
    print('1 - First name')
    print('2 - Last name')
    print('3 - Hair color')
    print('4 - Eye color')
    print('5 - Age')
    print('6 - Exit to main menu\n')
    search_option = input('Enter option:\t')

    if search_option == '1' or search_option == 'First name' or search_option == 'first name':
        input('Enter the first name of the user you are looking for:\t')

Any and all help is much appreciated!!任何和所有的帮助都非常感谢!!

Depending on your project, using a dictionary might be difficult in the future.根据您的项目,将来使用字典可能会很困难。 Let's not go down a dark road.我们不要走黑暗的道路。 Take a moment and assess the situation.花点时间评估一下情况。

We know that we want to collect some information from the user, such as:我们知道我们要从用户那里收集一些信息,例如:

  • first name
  • last name
  • hair color发色

...etc ...等等

We also want to store the User object to retrieve later based on a particular ID .我们还想存储User对象,以便稍后根据特定ID检索。 In your code, you search for other users based on attributes, but what if two or more users share the same attribute, for example, first name?在您的代码中,您根据属性搜索其他用户,但是如果两个或多个用户共享相同的属性(例如名字)怎么办?

What your asking for are attributes associated with a particular user.您要求的是与特定用户相关联的属性。 Why not create a class called User ?为什么不创建一个名为Userclass

 class User:


    def __init__(self, id, first_name, last_name, hair_color):

        # You can also check if any attributes are blank and throw an exception.
        self._id = id
        self._first_name = first_name
        self._last_name = last_name
        self._hair_color = hair_color

        # add more attributes if you want

    # a getter to access the self._id property
    @property
    def id(self):
        return self._id

    def __str__(self):
        return f"ID: {self._id} Name: {self._first_name} {self._last_name}  
        Hair Color: {self._hair_color}"

In your main function, you can now ask for the user details and store them in a class which you can append to a List .在您的主函数中,您现在可以询问用户详细信息并将它们存储在您可以附加到List

from User import User

def ask_for_input(question):
    answer = input(question)
    return answer.strip() # strip any user created white space.

def main():

   # Store our users
   users = []

   # Collect the user info
   id = ask_for_input(question = "ID ")
   first_name = ask_for_input(question = "First Name ")
   last_name = ask_for_input(question = "Last Name ")
   hair_color= ask_for_input(question = "Hair Color ")

   # Create our user object
   user = User(id=id, first_name=first_name, last_name=last_name, hair_color=hair_color)
   print(user)

   # accessing the id property
   print(user.id)

   users.append(user)

if __name__ == '__main__':
    main()

You may also want to improve on the above class, for example, error checking, and adding type hints to make the code more readable.您可能还想对上述类进行改进,例如,错误检查,以及添加类型提示以使代码更具可读性。

If you're just storing the user information, a data class might be more appropriate.如果您只是存储用户信息,数据类可能更合适。

If your looking for a broad suggestion, you could use mongob, it makes a great way to store data to be retrieved later, here is an example i built for another question.如果您正在寻找广泛的建议,您可以使用 mongob,它是存储数据以供以后检索的好方法,这是我为另一个问题构建的示例。 The prerequisites is that you'd have to get the mongod server running before you can use the pip install:先决条件是您必须先运行 mongod 服务器,然后才能使用 pip install:

Here is an example of how to get it going and how easy it easy to retrieve data like yours这是一个示例,说明如何进行操作以及检索像您这样的数据是多么容易

pip3 install pymongo
from pymongo import MongoClient
client = MongoClient()

client = MongoClient('localhost', 27017)

db = client.pymongo_test

posts = db.posts
post_data = {
    'title': 'The title of this post',
    'content': 'pymongo is awesome',
    'author': 'Bill'
}
result = posts.insert_one(post_data)
print('One post: {0}'.format(result.inserted_id))

bills_post = posts.find_one({'author': 'Bill'})
print(bills_post)


#One post: 5dc61c0cc2b75ebc458da31f
#{'_id': ObjectId('5dc61bf76071bde943ca262b'), 'title': 'The title of this post', 'content': 'pymongo is awesome', 'author': 'Bill'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM