怎么使用python中super()方法?
想必大家在编写代码,尤其是类的集成,会经常使用super这个方法吧,因此这个方法作用非常大,具体要怎么去利用呢?一起来看下吧~
为什么要用super?
1、让代码维护更加简单
Python是一门面向对象的语言,定义类时经常用到继承的概念,既然用到继承就少不得要在子类中引用父类的属性,我们可以通过“父类名.属性名”的方式来调用,代码如下:
class A: def fun(self): print('A.fun') class B(A): def fun(self): A.fun(self) print('B.fun')
一旦A类类名改了,我们就要分别到那几十上百个子类中修改,不但要改继承时用到的A类名,调用A类方法时用到的A类名也要改,繁琐的很,用super就好多了:
class A: def fun(self): print('A.fun') class B(A): def fun(self): super().fun() print('B.fun')
2、解决多继承带来的重复调用(菱形继承)、查找顺序(MRO)问题
Python是的继承机制是多继承,还是用这种方法来调用父类属性就会就回带来许多问题。假如有A、B、C、D这4个类,继承关系如下,我们要在各子类方法中显式调用父类的方法(姑且不考虑是否符合需求):
用“父类名.属性名” 的方式调用,代码如下:
class A: def fun(self): print('A.fun') class B(A): def fun(self): A.fun(self) print('B.fun') class C(A): def fun(self): A.fun(self) print('C.fun') class D(B , C): def fun(self): B.fun(self) C.fun(self) print('D.fun') D().fun()
输出结果为:
A.fun B.fun A.fun C.fun D.fun
A类被实例化了两次。这就是多继承带来的重复调用(菱形继承)的问题。使用super可以很好的解决这一问题:
class A: def fun(self): print('A.fun') class B(A): def fun(self): super(B , self).fun() print('B.fun') class C(A): def fun(self): super(C , self).fun() print('C.fun') class D(B , C): def fun(self): super(D , self).fun() print('D.fun') D().fun()
输出结果如下:
A.fun C.fun B.fun D.fun
怎么用super?
super是一个类(不是方法),实例化之后得到的是一个代理的对象,而不是得到了父类,并且我们使用这个代理对象来调用父类或者兄弟类的方法。使用格式如下:
super([type[, object-or-type]])
将这个格式展开来就有一下几种传参方式:
super() super(type , obj) super(type_1 , type_2)
注意:可没有super(type)这种方式
因此大家了解为什么要用super方法,以及怎么用super方法了嘛?如需了解更多python实用知识,点击进入JQ教程网Python大全。
您可能感兴趣的文章:
怎么使用python中super()方法?
Python中如何调用基类的成员方法
如何使用python super函数调用父类?
python3类中的super如何调用?
五分钟读懂Python中super().__init__和Base.__init__的区别
python3顶层父类多次循环怎么办?
python怎么实现单例模式
Java中this与super的用法与对比总结
super.super.xxx为什么不行
Java中super关键字用法介绍