2017-01-30 23 views
0

我是Python中的新手,如果问题对您来说非常简单,请耐心等待。无法在方法重载中输出子类变量

有人可以解释为什么Dog类中的类变量,名称在以下示例中导致错误?对于我来说d.name可以被调用是没有意义的,但d.eat()对于方法重载是不好的。非常感谢您的帮助!

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 ! 
+0

参见:http://stackoverflow.com/questions/14299013/namespaces-within-a-python-class –

回答

3

由于name是一个类的成员变量,而不是一个全局和局部变量,它需要.运营商来关注一下吧。试试其中一个:

print self.name 
    print Dog.name 

你使用哪一个将取决于你的程序设计的其他方面。第一个将尝试在当前对象中查找name,如果需要,可以回退到类定义。第二个将始终使用类定义。

+0

请突出的区别这两个'.name's,因为它很大。 – 9000

+0

@ 9000 - 谢谢。 –

0

出现错误的原因是因为您无法在该范围内使用变量名称定义方法。如果你这样做,那么你将不会有错误:

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!