Guano
Guano

Reputation: 159

Python difficulties with lists and loop

I have this code that gives me weird errors. Below you should see that code. First of i have my CombatEngine that basically just simulates a shoot out between me the player and the list of enemies. In the class TheBridge i make a instance of the combatengine and give it a list of enemies in the constructor(i code mostly in c#) but when i run the the combat method on the engine an error will be returned

AttributeError: type object 'GothonTrooper' has no attribute 'health'

I really dont understand how that is possible when its clear that health is defined for the GothonTrooper class. I suppose the error occurs in the combat method itself some point around when the individual enemy is found from the randint function.

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)

Upvotes: 0

Views: 73

Answers (2)

super_pippo
super_pippo

Reputation: 11

Sorry,my English is poor. Look at your define,the fourth GothonTrooper don't have () ,so as to AttributeError: type object GothonTrooper has no attribute health

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

Upvotes: 1

Anthony Forloney
Anthony Forloney

Reputation: 91786

Assuming what you have provided in your code is not a typo, the missing () in one of your GothonTrooper objects in your enemies list is the culprit. Without it, that object is never instatiated. Therefore that item will not yet have the health attribute.

To better illustrate where the problem is stemming from, the below example uses the dir method to return properties available on that object, (notice that health is missing on the second print line)

>>> 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__']

Upvotes: 1

Related Questions