具有用户输入的类的示例 [英] Example of Class with User Input

查看:52
本文介绍了具有用户输入的类的示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在(尝试)学习类时,我在网上看到的大多数示例中,类的实例都是由程序员定义的。有什么方法可以创建类的实例,其中存储该类的变量是由用户定义的吗?

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?

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

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?

推荐答案

大致有两种方法可以做到:

There are broadly two ways of doing it, either:


  1. 将输入完全放在类之外,然后像平常一样将其传递给 __ init __

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

一个更简单的概念;或

在类中输入内容,例如使用类方法:

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

然后称呼它:

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).

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

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

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

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

这篇关于具有用户输入的类的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆