我正在寻找通过用户输入创建类的实例 [英] I am looking to create instances of a class from user input
问题描述
我有这个课程:
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())
这篇关于我正在寻找通过用户输入创建类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!