python super方法

普通繼承
class FooParent(object): 
    def __init__(self): 
        self.parent = 'I\'m the parent.' 
        print 'Parent' 
     
    def bar(self,message): 
        print message, 'from Parent' 
         
class FooChild(FooParent): 
    def __init__(self): 
        FooParent.__init__(self) 
        print 'Child' 
         
    def bar(self,message): 
        FooParent.bar(self,message) 
        print 'Child bar function.' 
        print self.parent 
         
if __name__=='__main__': 
    fooChild = FooChild() 
    fooChild.bar('HelloWorld')
super繼承
class FooParent(object): 
    def __init__(self): 
        self.parent = 'I\'m the parent.' 
        print 'Parent' 
     
    def bar(self,message): 
        print message,'from Parent' 
 
class FooChild(FooParent): 
    def __init__(self): 
        super(FooChild,self).__init__() 
        print 'Child' 
         
    def bar(self,message): 
        super(FooChild, self).bar(message) 
        print 'Child bar fuction' 
        print self.parent 
 
if __name__ == '__main__': 
    fooChild = FooChild() 
    fooChild.bar('HelloWorld')
運行結果
Parent
Child
HelloWorld from Parent
Child bar fuction
I'm the parent.

從運行結果上看,普通繼承和super繼承是同樣的。可是其實它們的內部運行機制不同,這一點在多重繼承時體現得很明顯。code

  • 在super機制裏能夠保證公共父類僅被執行一次,至於執行的順序,是按照mro進行的(E.mro)。
  • 這裏是列表文本注意super繼承只能用於新式類,用於經典類時就會報錯。 新式類:必須有繼承的類,若是沒什麼想繼承的,那就繼承object 經典類:沒有父類,若是此時調用super就會出現錯誤:『super() argument 1 must be type, not classobj』
相關文章
相關標籤/搜索