2017-01-30 24 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!