跳转到主内容
极星编程网:以代码为星,赴技术山海!

Python中的super函数理解

super()函数根据传进去的两个参数具体作用如下: 通过第一参数传进去的类名确定当前在MRO中的哪个位置。MRO(Method Resolution Order); 通过第二个参数传进去的self,确定当前的MRO列表。
def super(cls, inst): mro = inst.__class__.mro() #确定当前MRO列表 return mro[mro.index(cls) + 1] #返回下一个类
如下代码:
class A(object): def name(self): print('name is xiaoming') #super(A,self).name()class B(object): def name(self): print('name is cat')class C(A,B): def name(self): print('name is wang') super(C,self).name()if __name__ == '__main__': c = C() print(c.__class__.__mro__) c.name()
执行以上代码输出:当执行C类下的super()函数时,实际调用了A类下的name函数。A中注释掉了super()函数,所以并没有向后继续执行。并且打印出了当前MRO列表顺序为C,A,B,object. 立即学习 “ Python免费学习笔记(深入) ”;
(, , , )name is wang name is xiaoming
当我们把A类中的注释去掉后,执行代码输出:可以看到,当A执行后继续执行了B中的name()函数。如果B中仍然有super函数则会继续向上去查找object中是否有name()函数。
(, , , )name is wang name is xiaoming name is cat
更多Python中的super函数理解相关文章请关注PHP中文网!

相关文章