未定义python namerror名称

时间:2015-12-14 16:21:14

标签: python class nameerror

我无法弄清楚为什么会收到此错误。我的代码就是这个

#define the Animal Class

class Animal:
    def __init__ (self, animal_type, age, color):
        self.animal_type = animal_type
        self.age = age
        self.color = color

    def makeNoise():
        pass

    def __str__(self):
        print ("% is % years old and is %" % animal_type,age, color)


#define child classes of Animal 
class Wolves(Animal):
    def __init__(self, animal_type, age, color, wild):

        Animal.__init__(self, animal_type, age, color)
        self.wild = wild
    def __str__(self):
        print ("% is % years old and is % and is %" % (animal_type, age, color, wild))

class Bear(Animal):
    def __init__ (self, animal_type, age, color, sex):
        self.sex = sex
        Animal.__init__(self,animal_type, age, color)

class Moose(Animal):
    def __init__(self, animal_type, age, color, antlers):
        self.antlers = antlers
        Animal.__init__(self, animal_type, age, color)

#add items to each class

wally = Wolves("wolf", 4, "grey","wild")
sally = Wolves("wolf", 3, "white", "tame")

print (str(sally))
print (str(wally))

并且完整的追溯是

Traceback (most recent call last):
  File "//mgroupnet.com/RedirectedFolders/SBT/Documents/bear51.py", line 41, in <module>
    print (str(sally))
  File "//mgroupnet.com/RedirectedFolders/SBT/Documents/bear51.py", line 24, in __str__
    print ("% is % years old and is % and is %" % (animal_type, age, color, wild))
NameError: name 'animal_type' is not defined

我做错了什么?

3 个答案:

答案 0 :(得分:1)

哦 - 基本上你只是忘了在self.animal_type方法中使用__str__。像这样:

def __str__(self):
    print ("%s is %s years old and is %s" % self.animal_type,self.age, self.color)

就像在__init__中一样,要使用实例化类中的变量,您需要使用&#34; self&#34;,就像在&#34;中来自我正在工作的动物实例上&#34;

答案 1 :(得分:0)

在Python中,方法只是普通函数。因此,您无法从另一个方法中的一个方法访问局部变量。在方法之间共享信息的典型方法是self。要在animal_type中获取__str__,您需要使用self.animal_type。类中的方法没有特殊的名称空间。这意味着就名称的可见性而言,如果您在一个模块或类中的方法中编写函数,则无关紧要。

答案 2 :(得分:0)

在Python中,self不是Java中的this关键字。它只是一个与其他参数一样的参数,按惯例,它通常称为self

当您调用方法时,例如some_animal.__str__() 1 ,这实际上只是Animal.__str__(some_animal)的语法糖,其中some_animal绑定到{{1}参数。

因此,在Java(以及许多其他语言)中,self表示&#34;查看此属性的当前实例&#34;并且是明确的(当没有相同名称的局部变量时)是可选的,但Python this不是可选的。它只是一个常规方法参数。

1 self不是一个很好的例子,因为你从不以这种方式称呼它,而是__str__,但你知道我的意思

相关问题