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