普通继承: 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") 结果 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") ================================================================================ 从运行结果上来看普通继承跟super继承是一样的,但是其实它们的内部运行机制不太一样,这一点在多重继承时体现得很明显。在super机制里可以保证公共父类仅被执行一次,至于执行的顺序,是按照mro进行的(E.__mro__)。(http://hi.baidu.com/thinkinginlamp/item/3095e2f52c642516ce9f32d5) 注意super继承只能用于新式类,用于经典类时就会报错。 新式类:必须有继承的类,如果没什么想继承的,那就继承objcet 经典类:没有父类,如果此时调用super就会出现错误:“super() argument 1 must be type, not classobj” |
|