我正在寻找通过用户输入创建类的实例

编程入门 行业动态 更新时间:2024-10-24 17:33:26
本文介绍了我正在寻找通过用户输入创建类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有这个课程:

class Bowler: def __init__(self, name, score): self.name = name self.score = score def nameScore(self): return '{} {}'.format(self.name, self.score)

我需要获得用户输入,直到输入空白行。然后使用获得的数据创建类的实例。我在想类似的东西:

I need to get user input until a blank line is entered. Then use the data I got to create instances of a class. I was thinking something like:

def getData(): name, score = input("Please enter your credentails (Name score): ").split() B1 = Bowler(name, score) print(B1.nameScore())

但是后来我不得不以某种方式循环它,直到得到空白的用户输入为止。

But then I would somehow have to loop it until I get a blank user input. Also I would somehow have to create B2 B3 B4 etc in the loop.

对不起,我还是编程新手,也许我是从错误的角度来看的。

Sorry I am still really new to programming, maybe I am looking at this from the wrong angle.

推荐答案

您要查找的是 Python列表。使用这些,您可以在运行循环时跟踪新创建的项目。要创建一个列表,我们只需像这样定义它:

What you're looking for are Python Lists. With these you will be able to keep track of your newly created items while running the loop. To create a list we simply defined it like so:

our_bowlers = []

现在,我们需要更改 getData 函数以返回无或新的 Bowler :

Now we need to alter our getData function to return either None or a new Bowler:

def getData(): # Get the input our_input = input("Please enter your credentails (Name score): ").split() # Check if it is empty if our_input == '': return None # Otherwise, we split our data and create the Bowler name, score = our_input.split() return Bowler(name, score)

然后运行一个循环,检查一个新的 Bowler ,如果没有得到任何东西,我们可以打印所有的 Bowlers 我们创建了:

and then we can run a loop, check for a new Bowler and if we didn't get anything, we can print all the Bowlers we created:

# Get the first line and try create a Bowler bowler = getData() # We loop until we don't have a valid Bowler while bowler is not None: # Add the Bowler to our list and then try get the next one our_bowlers.append(bowler) bowler = getData() # Print out all the collected Bowlers for b in our_bowlers: print(b.nameScore())

更多推荐

我正在寻找通过用户输入创建类的实例

本文发布于:2023-11-28 12:58:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1642502.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实例   用户

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!