Python 具有用户输入的类示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32721580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:07:35  来源:igfitidea点击:

Example of Class with User Input

pythonclasspython-2.7instance

提问by Joseph Farah

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:

这是来自另一个 SO 问题的对象示例:

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?

如何更改,以便用户可以基于类创建实例?

采纳答案by jonrsharpe

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()
    
  1. 让输入完全在类之外,然后__init__像往常一样将其传递给:

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

    这可以说是一个更简单的概念;或者

  2. 在类中获取输入,例如使用类方法:

    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: ')),
            )
    

    然后称之为:

    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'tbe unique):

如果您想拥有多个用户,您可以使用唯一键将他们保存在字典中(例如他们的userid- 请注意 Stack Overflow 允许多个用户具有相同的名称,因此不会是唯一的):

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:

然后每个用户都可以作为users[id_of_user]. 您可以添加检查以拒绝具有重复 ID 的用户,如下所示:

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

回答by Anvesh Arrabochu

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)