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 个解决方案
#1
-1
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
#2
1
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.
错误的原因不是print witch.enemy_name行(它会引发AttributeError,而不是NameError),而是self.name = enemy_name(敌人.__ init__中的第一行) - 参数被命名(没有双关语) name,而不是enemy_name。请注意,全局语句仅在函数体中有用,并且它不定义变量,它仅指定在当前函数中将名称视为全局。
#1
-1
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
#2
1
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.
错误的原因不是print witch.enemy_name行(它会引发AttributeError,而不是NameError),而是self.name = enemy_name(敌人.__ init__中的第一行) - 参数被命名(没有双关语) name,而不是enemy_name。请注意,全局语句仅在函数体中有用,并且它不定义变量,它仅指定在当前函数中将名称视为全局。