Python namerror name undefined

It’s hard for me to understand why I get this error. My code is

#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))

and the full feedback is

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

What am I doing wrong?

+4
source share
3 answers

Oh - well, basically you just forgot to use it self.animal_typein your method __str__. For example:

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

As in __init__, to use the variables from your instance of the class, you need to use the "I" as in "from this instance of the animal I'm working on."

+1
source

Python - . . self. animal_type __str__, self.animal_type. . , , .

0

Python self , this Java. , , , , self.

, some_animal.__str__() 1 Animal.__str__(some_animal), some_animal self.

Thus, in Java (and many other languages) it thismeans “look at the current instance for this attribute” and is optional if it is unambiguous (that is, when there is no local variable with the same name), but Python is selfnot required. This is just a normal method parameter.


1 is__str__ not a good example, since you never call it that way, but rather str(some_animal), but you know what I mean

0
source

Source: https://habr.com/ru/post/1619937/


All Articles