super 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。总之前人留下的经验就是:保持一致性。要不全部用类名调用父类,要不就全部用 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继承是一样的。但是其实它们的内部运行机制不一样,这一点在多重继承时体现得很明显。在super机制里可以保证公共父类仅被执行一次,至于执行的顺序,是按照mro进行的(E.__mro__)。
注意super继承只能用于新式类,用于经典类时就会报错。
新式类:必须有继承的类,如果没什么想继承的,那就继承object
经典类:没有父类,如果此时调用super就会出现错误:『super() argument 1 must be type, not classobj』
关于super用法的详细研究可参考「https://www.jb51.net/article/66912.htm」
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
更新日志
- 【原神手游】5.1版本更新维护预告
- 李锦华.1987-日与夜(LP版)【SOLO】【WAV+CUE】
- 伍珂玥.2014-伍珂玥【湾彩星辰】【FLAC分轨】
- 吕方.2001-旧情人·老情歌精选2CD【华纳】【WAV+CUE】
- 《星际战士2》¥219,《100% 鲜橙汁》¥7
- 手办鉴赏室:少女眼神颇有杀意!连衣裙勾勒傲人轮廓
- 未来可期的二次元大逃杀游戏——《白厄战境》简评
- 炉石传说死亡骑士卡组怎么搭配 死亡骑士最新卡组2024推荐
- 魔兽世界地下堡珍玩怎么升级 地下堡珍玩升级方法攻略分享
- 魔兽世界怎么获得泽克维尔的残血珍玩 泽克维尔的残血珍玩获取方式
- FrankSinatra-StrangersInTheNight(1966Jazz)[Flac24-96]
- 大原樱子《CAMON+5thAnniversaryBest~》2CD[24-96]flac
- Isgaard2003-GoldenKey(LimitedEdition)【WAV+CUE】
- 《合金装备3RE》伊娃定妆照公布:没被政确太好了
- 石家庄新增《黑神话:悟空》墙绘:小狐狸萍萍