涛子 - 简单就是美

成单纯魁增,永继振国兴,克复宗清政,广开家必升

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

普通继承

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('Hello World!')
# output
Parent
Child
Hello World! 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('Hello World!')
# output
Parent
Child
Hello World! from Parent
Child bar function.
I'm the parent.
posted on 2015-08-26 16:20  北京涛子  阅读(174)  评论(0)    收藏  举报