在循环中创建实例

时间:2015-02-28 18:22:27

标签: python class instances

我上周开始在游戏开发中学习课程。类。我试图创建一些东西,允许我在for循环中创建一些东西的实例。例如,我试图在循环中创建5个Player实例,并使用每次循环循环时都会增加的ID号。我已经走到了这一步。

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

我设法创建了5个Joe的实例,这很好,但是如何增加ID#?

3 个答案:

答案 0 :(得分:0)

    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

使用Var玩家并将其放入班级

答案 1 :(得分:0)

我会将你的玩家放在一个阵列中,这样他们就可以在循环范围之外使用。

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]

答案 2 :(得分:0)

您可以使用列表:

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