Python: I'm getting an error when using self.name

196 views Asked by At

I made 2 programs, one that works here:

class dog:
    amount_of_dogs = 0

    def __init__(self, name, playfulness):

        self.name = name
        self.playfulness = playfulness
        dog.amount_of_dogs += 1

dog1 = dog("Ruffer", 1000)

dog2 = dog("Skipper", 400)

dog3 = dog("El Diablo", 30000000)
print "The dog names are:", dog1.name, ",", dog2.name, ",", dog3.name, "."
print dog1.name, "'s happiness is ", dog1.playfulness, "!"
print dog2.name, "'s happiness is ", dog2.playfulness, "!"
print dog3.name, "'s happiness is ", dog3.playfulness, "!"

It works, no prob! But then, I made a second, longer program (This is just a snippet)

class enemy:
    global enemy_attack
    global enemy_health
    global enemy_name

    amount_of_enemies = 0

    def __init__(self, name, enemy_attack, enemy_health):
        self.name = enemy_name
        self.enemy_attack = enemy_attack
        self.enemy_health = enemy_health
        enemy.amount_of_enemies += 1

"""ENEMY STATS"""   
witch = enemy("witch", 40, 200)

print witch.enemy_name, witch.enemy_attack, witch.enemy_health

It throws the error:

enemy_name is not defined!

Why?

2

There are 2 answers

4
Cory Kramer On BEST ANSWER

You are trying to print

print witch.enemy_name

But the attribute is

self.name = enemy_name

So you should be calling

print witch.name
0
bruno desthuilliers On

The cause of the error is not the print witch.enemy_name line (which would have raised an AttributeError, not a NameError), but the self.name = enemy_name (first line in enemy.__init__) - the parameter is named (no pun) name, not enemy_name. Note that the global statement is only useful within a function body, and that it does not define a variable, it only specifies that in the current function the name is to be considered as global.