0

I am a newbie in Python so please bear with me if the question is very simple for you.

Can someone explain why the class variable, name, in Dog class causes an error in the following example? It doesn't make sense to me that d.name is ok to be called, but d.eat() is not ok for method overloading. Thank you very much in advance for your help!

class Animal:          # parent class
    name = 'Animal' 
    def eat(self):
        print "Animal eating"
class Dog(Animal):     # child class
    name = 'Dog' 
    def eat(self):  
        print name

d = Dog()
print d.name  # OK
d.eat()       # Error !
LED Fantom
  • 1,229
  • 1
  • 12
  • 32

2 Answers2

3

Since name is a class member variable, not a global nor local variable, it needs the . operator to look it up. Try one of these:

    print self.name
    print Dog.name

Which one you use will depend upon other aspects of your program design. The first will attempt to look up name in the current object, falling back to the class definition if required. The second will always use the class definition.

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
0

The reason for your error is because you can't define the method with the variable name within that scope. If you do this, then you won't have the error:

class Animal:          # parent class
    name = 'Animal'
    def eat(self):
        print "Animal eating"
class Dog(Animal):     # child class
    name = 'Dog'
    def eat(self):
        # name does not exist within this scope
        print self.name
d = Dog()
print d.name  # OK
d.eat()       # No longer an error!
tmwilson26
  • 741
  • 5
  • 17