Creating instances in a loop

拥有回忆 提交于 2019-12-12 03:09:38

问题


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


来源:https://stackoverflow.com/questions/28785217/creating-instances-in-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!