I am looking to create instances of a class from u

2019-02-26 09:28发布

问题:

I Have this class:

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.

回答1:

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 = []

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)

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


回答2:

This is my code to do what you want:

class Bowler:
    def __init__(self, name, score):
        self.name = name
        self.score = score

    def nameScore(self):
        return '{} {}'.format(self.name, self.score)

def getData():
    try:
        line = input("Please enter your credentails (Name score): ")
    except SyntaxError as e:
        return None
    name, score = line.split()
    score = int(score)
    B = Bowler(name, score)
    print(B.nameScore())
    return B

if __name__ == '__main__':
    bowlers = list()
    while True:
        B = getData()
        if B == None:
            break
        bowlers.append(B)

    for B in bowlers:
        print(B.nameScore())

In addition, I recommend you to modify your input for it's inconvenient now