Python在列表和循环方面的困难
我有一段代码,它给了我奇怪的错误。下面您应该看到该代码。 首先,我有我的战斗引擎,基本上只是模拟我,玩家和敌人之间的枪战。在TheBridge类中,我创建了combatengine的一个实例,并在构造函数中给它一个敌人列表(我的代码主要是c#),但是当我在引擎上运行combat方法时,会返回一个错误 AttributeError:type对象“Gothontroper”没有属性“health” 我真的不明白,如果很明显,健康是为GothonTrooper类定义的,那怎么可能。我想,当从randint函数中找到单个敌人时,错误发生在作战方法本身的某个点上Python在列表和循环方面的困难,python,list,while-loop,Python,List,While Loop,我有一段代码,它给了我奇怪的错误。下面您应该看到该代码。 首先,我有我的战斗引擎,基本上只是模拟我,玩家和敌人之间的枪战。在TheBridge类中,我创建了combatengine的一个实例,并在构造函数中给它一个敌人列表(我的代码主要是c#),但是当我在引擎上运行combat方法时,会返回一个错误 AttributeError:type对象“Gothontroper”没有属性“health” 我真的不明白,如果很明显,健康是为GothonTrooper类定义的,那怎么可能。我想,当从randi
class TheBridge(Scene):
def __init__(self):
enemies = [GothonTrooper(), GothonTrooper(), GothonTrooper(), GothonTrooper, GothonTrooper()]
self.the_bridge_combat = CombatEngine(enemies)
...
class CombatEngine(object):
def __init__(self, enemies):
self.enemies = enemies
while len(self.enemies) != 0:
enemy = self.enemies[randint(0, len(self.enemies)-1)]
print "You shoot at the Gothon."
hit_or_miss = PLAYER.attack()
if hit_or_miss >= 5:
print "The shot hits the Gothon!"
enemy.health -= 10
print "The Gothon is down to %s health" % enemy.health
...
class GothonTrooper(Humanoid):
def __init__(self):
self.health = 100
def attack(self):
return randint(1,10)
假设您在代码中提供的内容不是打字错误,则您的
敌人
列表中的一个GothonTrooper
对象中缺少的()
就是罪魁祸首。没有它,这个物体永远不会稳定。因此,该项还没有健康属性
为了更好地说明问题的根源,下面的示例使用该方法返回该对象上可用的属性(请注意,第二行print
中缺少health
)
对不起,我的英语很差。看看你的定义,第四个GothonTrooper
没有()
,以便
AttributeError:
type对象gothontroper
没有属性health
enemies = [GothonTrooper(), GothonTrooper(), GothonTrooper(), GothonTrooper, GothonTrooper()]
你能展示一下完整的回溯吗?你的敌人列表中没有包含你的GothonTrooper
的括号,这是一个打字错误吗?我以前在C#中做不到这一点,谢谢你的帮助!谢谢你的帮助,它确实解决了我的问题,但我把答案给了安东尼,因为他是第一个给出答案的人
enemies = [GothonTrooper(), GothonTrooper(), GothonTrooper(), GothonTrooper, GothonTrooper()]