|
普通繼承: 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") 結(jié)果 Parent Child HelloWorld from Parent Child bar function. I'm the parent. ========================================================== 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 function. ' print self.parent if __name__ == '__main__': fooChild = FooChild() fooChild.bar("HelloWorld") ================================================================================ 從運行結(jié)果上來看普通繼承跟super繼承是一樣的,但是其實它們的內(nèi)部運行機制不太一樣,這一點在多重繼承時體現(xiàn)得很明顯。在super機制里可以保證公共父類僅被執(zhí)行一次,至于執(zhí)行的順序,是按照mro進行的(E.__mro__)。(http://hi.baidu.com/thinkinginlamp/item/3095e2f52c642516ce9f32d5) 注意super繼承只能用于新式類,用于經(jīng)典類時就會報錯。 新式類:必須有繼承的類,如果沒什么想繼承的,那就繼承objcet 經(jīng)典類:沒有父類,如果此時調(diào)用super就會出現(xiàn)錯誤:“super() argument 1 must be type, not classobj” |
|
|