Creating instances in a loop

2019-08-30 04:24发布

问题:

I just started to learn about classes last week in my game dev. class. I am trying to create something that will allow me to create instances of something while in a for loop. For example, I am trying to create 5 instances of Player in a loop and use an ID number that will increase with each time the loop loops. I've gotten this far.

class Player(object):
    def __init__(self, nm, am, wp, ht, ide):
        self.name = nm
        self.ammo = am
        self.weapon = wp
        self.health = ht
        self.id = ide

    def __str__(self):
        values = "Hi my name is " + self.name + "\n" + "Ammo: " + str(self.ammo) + "\n" + "Weapon: " + self.weapon + "\n" + "Health: " + str(self.health) + "\n" + "ID #: " + str(self.id)
        return values

def main():
    Players = 0
    while Players < 5:
        play1 = Player("Joe", 5, "Machine gun", 22, 1)
        print (play1)
        Players = Players + 1

I've managed to create 5 instances of Joe which is fine, but how would I increase the ID #?

回答1:

    class Player(object):
    def __init__(self, nm, am, wp, ht, ide):
        self.name = nm
        self.ammo = am
        self.weapon = wp
        self.health = ht
        self.id = ide

    def __str__(self):
        values = "Hi my name is " + self.name + "\n" + "Ammo: " + str(self.ammo) + "\n" + "Weapon: " + self.weapon + "\n" + "Health: " + str(self.health) + "\n" + "ID #: " + str(self.id)
        return values

def main():
    Players = 0
    while Players < 5:
        play1 = Player("Joe", 5, "Machine gun", 22, Players)
        print (play1)
        Players = Players + 1

Use The Var Players And Put It Into The Class



回答2:

I would put your players in an array so they can be used outside of the scope of the loop.

def main():
Players = 0
list_of_players = []
for i in range(5):
    list_of_players.append(Player("Joe", 5, "Machine gun", 22, i+1))
    print list_of_players[i]


回答3:

You can use a list:

players = []
while len(players) < 5:
    players.append(Player("Joe", 5, "Machine gun", 22, len(players) + 1))