普通繼承 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