分享

python普通继承方式和super继承方式

 Tech-d 2013-03-06
普通继承:
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








    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多