Python:我在使用self.name时遇到错误

时间:2015-06-17 16:27:01

标签: python oop self

我制作了两个程序,一个在这里工作:

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, "!"

它有效,没有概率!但后来,我制作了第二个更长的节目(这只是一个片段)

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

它抛出错误:

enemy_name is not defined!

为什么呢?

2 个答案:

答案 0 :(得分:1)

错误的原因不是print witch.enemy_name行(它会引发AttributeError,而不是NameError),而self.name = enemy_nameenemy.__init__中的第一行) - 参数被命名(无双关语)name,而不是enemy_name。请注意,全局语句仅在函数体中有用,并且它不定义变量,它仅指定在当前函数中将名称视为全局。

答案 1 :(得分:-1)

您正在尝试打印

print witch.enemy_name

但属性是

self.name = enemy_name

所以你应该打电话

print witch.name