NameError to Animal not being defined

class Animal(object):
  """Makes cute animals."""
  is_alive = True
  health = "good" 
  def __init__(self, name, age): = name
    self.age = age
  # Add your method here!
  def description(self):
      print self.age
  hippo = Animal("Jones", 13)
  Sloth = Animal("Harish", 4)
  Ocelot = Animal("Lanny", 9)


I thought this was correct but NameError to Animal not being defined kept showing. So I asked for solution and compared the whole thing. My answer is word to word the solution and still I get “good” only for hippo. It tells me that ‘Sloth’ is not defined. Is this a bug?

Also something weird I noticed in my absolute last bit of code is that if I don’t press spacebar after < print > the ‘print’ command in the next line appears blue. What is this for?

the instances of the class are generated within the class. Then outside the class, you try to access the instances which are not in the global scope.

Could you break this down for me? I did not get that.

It would help if you tell me what you didn’t understand.

You try to make instances of the class inside the class. Which can’t be, given the class needs to be defined before you can create a class instance/object.

My question is why is Sloth not recognized? the class is defined right at the top, right? Animals.
It is also initialized using the init method.

Now if I create an instance: hippo. it’s recognized.
But why is Sloth not.=?

you have a scope problem. The instances (Sloth and others) are defined within the class itself

when you try to access their health, you do so in the global name spaces

you should ask yourself what the right scope/place is to create the instances and access there health.

Thanks a ton! I reset my workspace and realized my problems has carried over from my previous code.

as you said, I removed the indentation before hippo, etc and it worked out. :smiley:

That is the literal action, but you need to understand what behavioral change occurs. That is the way you should view and read code :slight_smile: will come with time and practice

1 Like