时间:2021-07-01 10:21:17 帮助过:10人阅读
普通继承
代码如下:
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用法的详细研究可参考「http://www.bitsCN.com/article/66912.htm」