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

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

我制作了 2 个程序,其中一个在此处有效:

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!

为什么?

您正在尝试打印

print witch.enemy_name

但是属性是

self.name = enemy_name

所以你应该打电话给

print witch.name

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