Example of Class with User Input [closed]

陌路散爱 提交于 2019-12-30 07:48:20

问题


In most of the examples I have seen online while (trying to) learn classes, the instances of the classes are defined by the programmer. Are there any ways of creating an instance of a class where it the variable that stores the class is defined by the user?

This is an example of an object from another SO question:

class StackOverflowUser:
    def __init__(self, name, userid, rep): 
        self.name = name
        self.userid = userid
        self.rep = rep

dave = StackOverflowUser("Dave Webb",3171,500)

How can this be changed so that the user can create instances based off of the class?


回答1:


There are broadly two ways of doing it, either:

  1. Have the input entirely outside the class, and just pass it in to __init__ as normal:

    user = StackOverflowUser(
        raw_input('Name: '),
        int(raw_input('User ID: ')), 
        int(raw_input('Reputation: ')),
    )
    

    which is arguably a simpler concept; or

  2. Take input within the class, e.g. using a class method:

    class StackOverflowUser:
    
        def __init__(self, name, userid, rep): 
            self.name = name
            self.userid = userid
            self.rep = rep
    
        @classmethod
        def from_input(cls):
            return cls(
                raw_input('Name: '),
                int(raw_input('User ID: ')), 
                int(raw_input('Reputation: ')),
            )
    

    then call it like:

    user = StackOverflowUser.from_input()
    

I prefer the latter, as it keeps the necessary input logic with the class it belongs to, and note that neither currently has any validation of the input (see e.g. Asking the user for input until they give a valid response).


If you want to have multiple users, you could hold them in a dictionary using a unique key (e.g. their userid - note that Stack Overflow allows multiple users to have the same name, so that wouldn't be unique):

users = {}
for _ in range(10):  # create 10 users
    user = StackOverflowUser.from_input()  # from user input
    users[user.userid] = user  # and store them in the dictionary

Then each user is accessible as users[id_of_user]. You could add a check to reject users with duplicate IDs as follows:

if user.userid in users:
    raise ValueError('duplicate ID')



回答2:


Take input and store them in variables and use them to create the instance

 class StackOverflowUser:
        def __init__(self, name, userid, rep): 
            self.name = name
            self.userid = userid
            self.rep = rep

 name = raw_input("Enter name: ")
 userid = int(raw_input("Enter user id: "))
 rep = int(raw_input("Enter rep: "))

 dave = StackOverflowUser(name, userid, rep)


来源:https://stackoverflow.com/questions/32721580/example-of-class-with-user-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!