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.
1 Answer 1
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 / classIn the
Dogclass, you call the variablehas_fur, but in the parent class it's called justfur.
furtoself.furinsidereal_animal()will allow the code to run, it's an incomplete fix -- and unless you're going to makefuran instance variable (which it seems like you should), you might as well reference it asAnimal.furto avoid confusion. There's also the issue about the randomhas_furthat doesn't do anything at the moment.