Python NameError:名称未定义

4

我遇到了困难,无法确定为什么会出现这个错误。我的代码是这样的:

#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

我做错了什么?

6
你应该使用 self.animal_type, self.age, self.color 来调用实例属性。 - R Nar
1
在Java中,当不含歧义时,“this”是可选的,但在Python中,“self”不是可选的。 - tobias_k
我在你的帮助下解决了最初的问题。谢谢。 - Swiley
3个回答

1

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

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

就像在__init__中一样,要使用实例化类的变量,您需要使用"self",例如"从我正在处理的这个动物实例中"。


0
在Python中,方法只是普通函数。因此,您无法从一个方法中访问另一个方法的局部变量。在方法之间共享信息的典型方式是通过self。要在__str__中获取animal_type,需要使用self.animal_type。类中没有特殊的命名空间用于方法。这意味着在名称的可见性方面,无论您是在模块中编写函数还是在类中编写方法都没有关系。

0
在Python中,self与Java中的this不同,它只是一个像其他参数一样的参数,按照惯例通常称为self
当您调用一个方法,如some_animal.__str__()1时,这实际上只是Animal.__str__(some_animal)的语法糖,其中some_animal绑定到self参数。
因此,在Java(和许多其他语言)中,this表示“查看当前实例以获取该属性”,并且在不引起歧义的情况下(即没有同名的局部变量时),可选。但是Python的self不是可选项,它只是一个普通的方法参数。

1 __str__ 不是一个好的例子,因为你从来不会以这种方式调用它,而是使用 str(some_animal),但你知道我的意思。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接