Skip to main content
 首页 » 编程设计

python之我正在寻找根据用户输入创建类的实例

2025年01月19日10zdz8207

我有这门课:

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

在输入空白行之前,我需要获取用户输入。然后使用我得到的数据创建一个类的实例。我在想类似的事情:

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

但是我会以某种方式循环它直到我得到一个空白的用户输入。此外,我还必须在循环中创建 B2 B3 B4 等。

抱歉,我对编程还是很陌生,也许我从错误的角度看待这个问题。

请您参考如下方法:

您要找的是Python Lists .有了这些,您将能够在运行循环时跟踪新创建的项目。要创建一个列表,我们只需像这样定义它:

our_bowlers = [] 

现在我们需要更改我们的 getData 函数以返回 None 或一个新的 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,如果我们没有得到任何东西,我们可以打印我们创建的所有 Bowler:

# 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())