super 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。
MRO 就是类的方法解析顺序表, 其实也就是继承父类方法时的顺序表。
语法
以下是 super() 方法的语法:
super(<a href="https://www.gaodaima.com/tag/type" title="查看更多关于type的文章" target="_blank">type</a>[, object-or-type])
www#gaodaima.com来源gaodai#ma#com搞@@代~&码网搞代码
参数
type — 类。
object-or-type — 类,一般是 self
Python3.x 和 Python2.x 的一个区别是: Python 3 可以使用直接使用 super().xxx 代替 super(Class, self).xxx :
python3实例
class A: def add(self, x): y = x+1 print(y) class B(A): def add(self, x): super().add(x) b = B() b.add(2) # 3
学习python,尽在搞代码网!
来源:搞代码网:原文地址:https://www.gaodaima.com