2013-02-18 25 views
1

假設我有一個名爲Animal的類和一個名爲Dog的子類。我如何從Dog類訪問動物的定義unicodePython中的父__unicode__

class Animal: 
     def __unicode__(self): 
      return 'animal' 

class Dog(Animal): 
     def __unicode__(self): 
      return 'this %s is a dog' % (I want to get the Animal's __unicode__ here) 
+0

這是Python 2還是Python 3? (順便說一下,你的代碼缺少一些'def'關鍵字。) – 2013-02-18 09:56:55

+0

這是python 2.對,對於def的抱歉。 – 2013-02-18 09:57:32

回答

4

既然你在Python 2實施老式類,你只能通過其限定的名稱訪問的基類的方法:

class Animal: 
    def __unicode__(self): 
     return 'animal' 

class Dog(Animal): 
    def __unicode__(self): 
     return 'this %s is a dog' % Animal.__unicode__(self) 

不過,如果您修改的基類,使其成爲一個new-style class,那麼你可以使用super()

class Animal(object): 
    def __unicode__(self): 
     return 'animal' 

class Dog(Animal): 
    def __unicode__(self): 
     return 'this %s is a dog' % super(Dog, self).__unicode__() 

注意,所有的類都是在Python 3的新樣式類,所以super()總是可以運行該版本時使用。

+0

您應該使用python3: '{0}'。format(var) 而不是'%s'%(var)。 請參閱:http://docs.python.org/3.3/library/stdtypes.html#str.format – shakaran 2013-02-18 10:08:26

+0

@skaran,你是對的,但提問者使用Python 2,而不是3.我只是說' super()'可以在任何情況下使用,如果他曾經遷移到Python 3。 – 2013-02-18 10:09:27

+1

只需展開 - 在Python 3中,可以在不帶參數的情況下調用super(),因爲它是隱式的。但在Python 2.x中,它是明確的,所以需要'super(Dog,self)'。 – TyrantWave 2013-02-18 10:11:44

0

您可以在幾種方法引用父方法:

class Dog(Animal): 
     def __unicode__(self): 
      return 'this %s is a dog' % Animal.__unicode__(self) 

class Dog(Animal): 
    def __unicode__(self): 
      return 'this %s is a dog' % super(Dog, self).__unicode__() 

注:爲了使用超父類必須是一個新的樣式類。如果使用類似於問題中定義的舊類風格的類,則第二種方法將失敗。

+1

在發佈之前儘可能檢查代碼是最好的。如果你真的嘗試第二個建議,在Python 2上運行的'Animal'的OP定義中,你會得到'TypeError:必須是類型的,而不是classobj' – Duncan 2013-02-18 10:35:14

+0

@Duncan OP的定義? – Ifthikhan 2013-02-18 10:38:05

+0

@Duncan謝謝你指出這個問題。我沒有注意到動物是一個老式的課堂。 – Ifthikhan 2013-02-18 10:50:12