python之super的使用小结


Posted in Python onAugust 13, 2018

为什么需要super

在python没有引入super之前, 如果需要在子类中引用父类的方法, 一般写法如下:

class Father:
 def whoami(self):
  print("I am father")


class Child:
 def whoami(self):
  print("I am child")
  Father.whoami(self)

这样看好像没什么问题, 就算没有super也能正常调用父类的方法, 但是如果有一天Father类需要修改类名为Father1, 那么子类Child中也必须跟着修改.

想象下如果一个类有很多个子类, 这样一来我们就需要修改每个子类中引用父类的语句

怎么使用super

Help on class super in module builtins:

class super(object)
 | super() -> same as super(__class__, <first argument>)
 | super(type) -> unbound super object
 | super(type, obj) -> bound super object; requires isinstance(obj, type)
 | super(type, type2) -> bound super object; requires issubclass(type2, type)
 | Typical use to call a cooperative superclass method:
 | class C(B):
 |   def meth(self, arg):
 |     super().meth(arg)
 | This works for class methods too:
 | class C(B):
 |   @classmethod
 |   def cmeth(cls, arg):
 |     super().cmeth(arg)

我们来看看super的帮助文档, 首先super是一个类, 它的调用方法有如下几种:

1.super()
2.super(type)
3.super(type, obj)
4.super(type, type2)

我们推荐用第一种方法来使用super, 因为它并不需要显式传递任何参数.但是要注意一点, super只能在新式类中使用.

class A:
 def __init__(self):
  print("this is A")

class B(A):
 def __init__(self):
  super().__init__()
  print("this is B")

b = B()

"""
this is A
this is B
"""

看起来super就像直接调用了B的父类A的__init__, 其实并不是这样的, 我们看看super在多继承下的使用

class A:
 def __init__(self):
  print("this is A")
  print("leave A")

class B(A):
 def __init__(self):
  print("this is B")
  super().__init__()
  print("leave B")

class C(A):
 def __init__(self):
  print("this is C")
  super().__init__()
  print("leave C")
 

class D(B, C):
 def __init__(self):
  print("this is D")
  super().__init__()
  print("leave D")  
  
d = D()

"""
this is D
this is B
this is C
this is A
leave A
leave C
leave B
leave D
"""

print(D.__mro__)
"""
(<class '__main__.D'>, 
<class '__main__.B'>, 
<class '__main__.C'>, 
<class '__main__.A'>, 
<class 'object'>)
"""

这里可以看到, 如果super只是简单调用父类的方法的话, 那么调用了B的__init__ 方法之后, 应该调用A的__init__ 才对, 但是调用的却是C的__init__ 方法

这是因为super调用的是当前类在MRO列表中的后一个类, 而并不是简单地调用当前类的父类

python并没有强制性限制我们使用super调用父类, 我们还是可以使用原始的方法来调用父类中的方法, 但是需要注意的是调用父类的方法要统一, 即全用super或全不用super, 而用super 的话, 调用的方式也最好是统一的

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python中的包和模块实例
Nov 22 Python
Python中的探索性数据分析(功能式)
Dec 22 Python
微信跳一跳python辅助脚本(总结)
Jan 11 Python
Python paramiko模块的使用示例
Apr 11 Python
python pandas 对series和dataframe的重置索引reindex方法
Jun 07 Python
Pycharm设置去除显示的波浪线方法
Oct 28 Python
python读取txt文件中特定位置字符的方法
Dec 24 Python
python广度优先搜索得到两点间最短路径
Jan 17 Python
TensorFlow dataset.shuffle、batch、repeat的使用详解
Jan 21 Python
Python求两个字符串最长公共子序列代码实例
Mar 05 Python
Python decorator拦截器代码实例解析
Apr 04 Python
Python之Matplotlib绘制热力图和面积图
Apr 13 Python
Selenium控制浏览器常见操作示例
Aug 13 #Python
详解python3中的真值测试
Aug 13 #Python
利用Python将每日一句定时推送至微信的实现方法
Aug 13 #Python
Selenium鼠标与键盘事件常用操作方法示例
Aug 13 #Python
python删除字符串中指定字符的方法
Aug 13 #Python
Django contenttypes 框架详解(小结)
Aug 13 #Python
Python中的Numpy矩阵操作
Aug 12 #Python
You might like
php中有关字符串的4个函数substr、strrchr、strstr、ereg介绍和使用例子
2014/04/24 PHP
PHP JSON出错:Cannot use object of type stdClass as array解决方法
2014/08/16 PHP
php实现字符串首字母转换成大写的方法
2015/03/17 PHP
详解WordPress中添加友情链接的方法
2016/05/21 PHP
让Laravel API永远返回JSON格式响应的方法示例
2018/09/05 PHP
php curl操作API接口类完整示例
2019/05/21 PHP
PHP实现简单用户登录界面
2019/10/23 PHP
JavaScript下利用fso判断文件是否存在的代码
2010/12/11 Javascript
基于jQuery的倒计时实现代码
2012/05/30 Javascript
jQuery Migrate 1.1.0 Released 注意事项
2014/06/14 Javascript
Javascript基础教程之比较操作符
2015/01/18 Javascript
javascript内置对象操作详解
2015/02/04 Javascript
Bootstrap每天必学之折叠
2016/04/12 Javascript
vue.js开发环境安装教程
2017/03/17 Javascript
DataTables添加额外的查询参数和删除columns等无用参数实例
2017/07/04 Javascript
详解Angular2表单-模板驱动的表单(Template-Driven Forms)
2017/08/04 Javascript
vuejs使用FormData实现ajax上传图片文件
2017/08/08 Javascript
基于ES6作用域和解构赋值详解
2017/11/03 Javascript
浅谈微信JS-SDK 微信分享接口开发(介绍版)
2018/08/15 Javascript
mpvue全局引入sass文件的方法步骤
2019/03/06 Javascript
浅谈JS和jQuery的区别
2019/03/27 jQuery
js节流防抖应用场景,以及在vue中节流防抖的具体实现操作
2020/09/21 Javascript
python client使用http post 到server端的代码
2013/02/10 Python
Python实例之wxpython中Frame使用方法
2014/06/09 Python
python 将print输出的内容保存到txt文件中
2018/07/17 Python
对Python发送带header的http请求方法详解
2019/01/02 Python
python matplotlib拟合直线的实现
2019/11/19 Python
前端H5 Video常见使用场景简介
2020/08/21 HTML / CSS
世界领先的艺术图书出版社:TASCHEN
2018/07/23 全球购物
英超联赛的首选足球:Mitre足球
2019/05/06 全球购物
如何保障Web服务器安全
2014/05/05 面试题
房屋公证委托书
2014/04/03 职场文书
汽车4S店销售经理岗位职责
2015/04/02 职场文书
2015年党员创先争优公开承诺书
2015/04/27 职场文书
Vue.js中v-for指令的用法介绍
2022/03/13 Vue.js
PyTorch中的torch.cat简单介绍
2022/03/17 Python