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』
相关文章
相关标签/搜索