本文介绍了在循环中创建实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
上周我刚开始在游戏开发中学习课程。类。我试图创建一些东西,将允许我在一个for循环中创建一些东西的实例。例如,我试图在循环中创建 Player
的5个实例,并使用每次循环循环时增加的ID号。我已经到这里了。
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
我已经成功创建了 Joe
的5个实例,
I've managed to create 5 instances of Joe
which is fine, but how would I increase the ID #?
推荐答案
您可以使用列表:
players = []
while len(players) < 5:
players.append(Player("Joe", 5, "Machine gun", 22, len(players) + 1))
这篇关于在循环中创建实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!