Python列表和循环的困难

2024-09-28 17:17:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个代码,给我奇怪的错误。下面你应该看到代码。 首先,我有我的战斗引擎,基本上只是模拟一个枪战之间我的球员和敌人名单。在类TheBridge中,我创建了combatengine的一个实例,并在构造函数中为它提供了一个敌人列表(我主要用c#编写代码),但是当我在引擎上运行the-combat方法时,会返回一个错误

AttributeError:类型对象“gothontroper”没有属性“health”

我真的不明白这怎么可能,当它明确的健康是为GothonTrooper类定义。我假设这个错误发生在战斗方法本身的某个点上,当单个敌人从randint函数中被发现时。你知道吗

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)

Tags: the代码selfinitdef错误classprint
2条回答

对不起,我的英语很差。看看你的定义,第四个GothonTrooper没有(),所以 AttributeError:类型对象GothonTrooper没有属性health

enemies = [GothonTrooper(), GothonTrooper(), GothonTrooper(), GothonTrooper, GothonTrooper()]

假设您在代码中提供的不是打字错误,那么在enemies列表中的一个GothonTrooper对象中丢失的()就是罪魁祸首。没有它,这个物体就不会固定。因此,该项还没有health属性。你知道吗

为了更好地说明问题的根源,下面的示例使用^{}方法返回该对象上可用的属性(请注意,第二行health缺少print

>>> class Trooper():
    def __init__(self):
        self.health = "90%"


>>> enemies = [Trooper(), Trooper]
>>> for enemy in enemies:
       print(dir(enemy))


[..., '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'health']
[..., '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

相关问题 更多 >