0

New to python and currently learning about classes and OOP. I'm trying to get the following simple piece of code to run but can't figure out why I'm getting an error. Please see code below:

class Animal(object):
 fur = True
 def real_animal(self):
 if fur:
 print "Real animal"
 else:
 print "Fake animal"
class Dog(Animal):
 fur = True
 def __init__(self, name): 
 self.name = name
rover = Dog("Rover")
rover.real_animal()

I get an error stating fur is not defined. From my understanding, classes can inherit from classes. So, since Rover is-a instance of class Dog, which is a class Animal. Shouldn't I be able to run functions of base class Animal on Rover? I basically want to state dogs have fur and therefore are real animals.

Thanks all for helping a newbie.

JuniorCompressor
20.1k4 gold badges33 silver badges58 bronze badges
asked Mar 17, 2015 at 21:39
4
  • 1
    Is your indentation exactly as you have it above? Because that'll cause you problems... everything in the class needs to be indented under the class definition line. Commented Mar 17, 2015 at 21:43
  • @Ffisegydd while changing fur to self.fur inside real_animal() will allow the code to run, it's an incomplete fix -- and unless you're going to make fur an instance variable (which it seems like you should), you might as well reference it as Animal.fur to avoid confusion. There's also the issue about the random has_fur that doesn't do anything at the moment. Commented Mar 17, 2015 at 21:45
  • @JuniorCompressor - how do you know that is the code the OP had - perhaps he has messed up his indentation Commented Mar 17, 2015 at 21:45
  • @Mark Because he didn't have parse error Commented Mar 17, 2015 at 21:46

1 Answer 1

2

You have at least two mistakes:

  • You need to refer to the fur variable as self.fur, because it's not a local variable but a variable on the instance / class

  • In the Dog class, you call the variable has_fur, but in the parent class it's called just fur.

answered Mar 17, 2015 at 21:44
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.