super()方法
super()是一個(gè)調(diào)用父類的方法.
super()用來解決多繼承問題,直接用類名調(diào)用父類的方法在單繼承中是沒有問題的,但是如果使用多繼承會涉及到查找順序(MRO)、重復(fù)調(diào)用等種種問題。
python2.x實(shí)例
class A(object):passclass B(A):def add(self, x):super(B, self).add(x)python3.x實(shí)例
class A:passclass B(A):def add(self, x):super().add(x)實(shí)例
class FooParent(object):def __init__(self):self.parent = 'I\'m the parent.'print ('Parent')def bar(self,message):print ("%s from Parent" % message)class FooChild(FooParent):def __init__(self):# super(FooChild,self) 首先找到 FooChild 的父類(就是類 FooParent),然后把類B的對象 FooChild 轉(zhuǎn)換為類 FooParent 的對象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')執(zhí)行結(jié)果:
Parent Child HelloWorld from Parent Child bar fuction I'm the parent.?
轉(zhuǎn)載于:https://www.cnblogs.com/aaronthon/p/9700365.html
總結(jié)
- 上一篇: 抖音app是抖音极速版吗(抖音直播电脑版
- 下一篇: 快手极速版在哪里下载(上的快手极速版)