深入解析Python编程中super关键字的用法


Posted in Python onJune 24, 2016

官方文档中关于super的定义说的不是很多,大致意思是返回一个代理对象让你能够调用一些继承过来的方法,查找的机制遵循mro规则,最常用的情况如下面这个例子所示:

class C(B):
  def method(self, arg):
    super(C, self).method(arg)

子类C重写了父类B中同名方法method,在重写的实现中通过super实例化的代理对象调用父类的同名方法。

super类的初始方法签名如下:

def __init__(self, type1, type2=None): # known special case of super.__init__
    """
    super(type, obj) -> bound super object; requires isinstance(obj, type)
    super(type) -> unbound super object
    super(type, type2) -> bound super object; requires issubclass(type2, type)
    Typical use to call a cooperative superclass method:

除去self外接受一个或者或者两个参数,如同注释声明的一样,接受两个参数时返回的是绑定的super实例,省略第二个参数的时候返回的是未绑定的super对象。

一般情况下当调用继承的类方法或者静态方法时,并不需要绑定具体的实例,这个时候使用super(type, type2).some_method就能达到目的,当然super(type, obj)在这种情况下也能够使用,super对象有自定义实现的getattribute方法也能够处理。不过,后者一般用来调用实例方法,这样在查找方法的时候能够传入相应的实例,从而得到绑定的实例方法:

class A(object):
  def __init__(self):
    pass

  @classmethod
  def klass_meth(cls):
    pass

  @staticmethod
  def static_meth():
    pass

  def test(self):
    pass

class B(A):
  pass

>>> b = B()
>>> super(B, b).test
<bound method B.test of <__main__.B object at 0x02DA3570>>
>>> super(B, b).klass_meth
<bound method type.klass_meth of <class '__main__.B'>>
>>> super(B, b).static_meth
<function static_meth at 0x02D9CC70>
>>> super(B, B).test
<unbound method B.test>
>>> super(B, B).klass_meth
<bound method type.klass_meth of <class '__main__.B'>>
>>> super(B,B).satic_meth
>>> super(B,B).static_meth
<function static_meth at 0x02D9CC70>

初始化super对象的时候,传递的第二个参数其实是绑定的对象,第一个参感觉数可以粗暴地理解为标记查找的起点,比如上面例子中的情况:super(B, b).test就会在B.__mro__里面列出的除B本身的类中查找方法test,因为方法都是非数据描述符,在super对象的自定义getattribute里面实际上会转化成A.__dict['test'].__get__(b, B)。

super在很多地方都会用到,除了让程序不必hardcode指定类型让代码更加动态,还有其他一些具体必用的地方比如元类中使用super查找baseclass里面的new生成自定义的类型模板;在自定义getattribute的时候用来防止无限循环等等。

关于super建议读者将它与python的描述符一起来理解,因为super就实现了描述符的协议,是一个非数据描述符,能够帮助大家更好的理解super的使用和工作原理。

同时,有以下4个点值得大家注意:
1、单继承时super()和__init__()实现的功能是类似的

class Base(object):
  def __init__(self):
    print 'Base create'

class childA(Base):
  def __init__(self):
    print 'creat A ',
    Base.__init__(self)


class childB(Base):
  def __init__(self):
    print 'creat B ',
    super(childB, self).__init__()

base = Base()

a = childA()
b = childB()

输出结果:

Base create
creat A Base create
creat B Base create

使用super()继承时不用显式引用基类。

2、super()只能用于新式类中

把基类改为旧式类,即不继承任何基类

class Base():
  def __init__(self):
    print 'Base create'

执行时,在初始化b时就会报错:

super(childB, self).__init__()
TypeError: must be type, not classobj

3、super不是父类,而是继承顺序的下一个类

    在多重继承时会涉及继承顺序,super()相当于返回继承顺序的下一个类,而不是父类,类似于这样的功能:

def super(class_name, self):
  mro = self.__class__.mro()
  return mro[mro.index(class_name) + 1]

    mro()用来获得类的继承顺序。

例如:

class Base(object):
  def __init__(self):
    print 'Base create'

class childA(Base):
  def __init__(self):
    print 'enter A '
    # Base.__init__(self)
    super(childA, self).__init__()
    print 'leave A'


class childB(Base):
  def __init__(self):
    print 'enter B '
    # Base.__init__(self)
    super(childB, self).__init__()
    print 'leave B'

class childC(childA, childB):
  pass

c = childC()
print c.__class__.__mro__

输入结果如下:

enter A 
enter B 
Base create
leave B
leave A
(<class '__main__.childC'>, <class '__main__.childA'>, <class '__main__.childB'>, <class '__main__.Base'>, <type 'object'>)

    supder和父类没有关联,因此执行顺序是A —> B—>—>Base

    执行过程相当于:初始化childC()时,先会去调用childA的构造方法中的 super(childA, self).__init__(), super(childA, self)返回当前类的继承顺序中childA后的一个类childB;然后再执行childB().__init()__,这样顺序执行下去。

    在多重继承里,如果把childA()中的 super(childA, self).__init__() 换成Base.__init__(self),在执行时,继承childA后就会直接跳到Base类里,而略过了childB:

enter A 
Base create
leave A
(<class '__main__.childC'>, <class '__main__.childA'>, <class '__main__.childB'>, <class '__main__.Base'>, <type 'object'>)

 

    从super()方法可以看出,super()的第一个参数可以是继承链中任意一个类的名字,

    如果是本身就会依次继承下一个类;

    如果是继承链里之前的类便会无限递归下去;

    如果是继承链里之后的类便会忽略继承链汇总本身和传入类之间的类;

    比如将childA()中的super改为:super(childC, self).__init__(),程序就会无限递归下去。

    如:

File "C:/Users/Administrator/Desktop/crawler/learn.py", line 10, in __init__
  super(childC, self).__init__()
 File "C:/Users/Administrator/Desktop/crawler/learn.py", line 10, in __init__
  super(childC, self).__init__()
 File "C:/Users/Administrator/Desktop/crawler/learn.py", line 10, in __init__
  super(childC, self).__init__()
 File "C:/Users/Administrator/Desktop/crawler/learn.py", line 10, in __init__
  super(childC, self).__init__()
 File "C:/Users/Administrator/Desktop/crawler/learn.py", line 10, in __init__
  super(childC, self).__init__()
 File "C:/Users/Administrator/Desktop/crawler/learn.py", line 10, in __init__
  super(childC, self).__init__()
 File "C:/Users/Administrator/Desktop/crawler/learn.py", line 10, in __init__
  super(childC, self).__init__()
 File "C:/Users/Administrator/Desktop/crawler/learn.py", line 10, in __init__
  super(childC, self).__init__()
 File "C:/Users/Administrator/Desktop/crawler/learn.py", line 10, in __init__
  super(childC, self).__init__()
 File "C:/Users/Administrator/Desktop/crawler/learn.py", line 10, in __init__
  super(childC, self).__init__()
 File "C:/Users/Administrator/Desktop/crawler/learn.py", line 10, in __init__
  super(childC, self).__init__()
 File "C:/Users/Administrator/Desktop/crawler/learn.py", line 10, in __init__
  super(childC, self).__init__()
 File "C:/Users/Administrator/Desktop/crawler/learn.py", line 10, in __init__
  super(childC, self).__init__()
RuntimeError: maximum recursion depth exceeded while calling a Python object

4、super()可以避免重复调用

    如果childA基础Base, childB继承childA和Base,如果childB需要调用Base的__init__()方法时,就会导致__init__()被执行两次:

class Base(object):
  def __init__(self):
    print 'Base create'

class childA(Base):
  def __init__(self):
    print 'enter A '
    Base.__init__(self)
    print 'leave A'


class childB(childA, Base):
  def __init__(self):
    childA.__init__(self)
    Base.__init__(self)

b = childB()
  Base的__init__()方法被执行了两次

enter A 
Base create
leave A
Base create
使用super()是可避免重复调用

class Base(object):
  def __init__(self):
    print 'Base create'

class childA(Base):
  def __init__(self):
    print 'enter A '
    super(childA, self).__init__()
    print 'leave A'


class childB(childA, Base):
  def __init__(self):
    super(childB, self).__init__()

b = childB()
print b.__class__.mro()
enter A 
Base create
leave A
[<class '__main__.childB'>, <class '__main__.childA'>, <class '__main__.Base'>, <type 'object'>]
Python 相关文章推荐
详解Python的Django框架中manage命令的使用与扩展
Apr 11 Python
python自动翻译实现方法
May 28 Python
Python实现将不规范的英文名字首字母大写
Nov 15 Python
Python使用文件锁实现进程间同步功能【基于fcntl模块】
Oct 16 Python
使用python和Django完成博客数据库的迁移方法
Jan 05 Python
python3+PyQt5使用数据库窗口视图
Apr 24 Python
python sys.argv[]用法实例详解
May 25 Python
Python使用pickle模块报错EOFError Ran out of input的解决方法
Aug 16 Python
python统计指定目录内文件的代码行数
Sep 19 Python
python3+openCV 获取图片中文本区域的最小外接矩形实例
Jun 02 Python
python 常见的反爬虫策略
Sep 27 Python
selenium设置浏览器为headless无头模式(Chrome和Firefox)
Jan 08 Python
深入了解Python数据类型之列表
Jun 24 #Python
Python实现信用卡系统(支持购物、转账、存取钱)
Jun 24 #Python
Python提取Linux内核源代码的目录结构实现方法
Jun 24 #Python
Linux上安装Python的PIL和Pillow库处理图片的实例教程
Jun 23 #Python
尝试用最短的Python代码来实现服务器和代理服务器
Jun 23 #Python
Python基础篇之初识Python必看攻略
Jun 23 #Python
浅谈python中scipy.misc.logsumexp函数的运用场景
Jun 23 #Python
You might like
PHP生成静态HTML页面最简单方法示例
2015/04/09 PHP
学习php设计模式 php实现命令模式(command)
2015/12/08 PHP
CentOS下搭建PHP环境与WordPress博客程序的全流程总结
2016/05/07 PHP
PHP加密解密类实例代码
2016/07/20 PHP
thinkPHP框架对接支付宝即时到账接口回调操作示例
2016/11/14 PHP
CI(CodeIgniter)框架实现图片上传的方法
2017/03/24 PHP
php利用fsockopen GET/POST提交表单及上传文件
2017/05/22 PHP
PHP实现打包下载文件的方法示例
2017/10/07 PHP
获取dom元素那些讨厌的位置封装代码
2010/06/23 Javascript
JS+CSS实现另类带提示效果的竖向导航菜单
2015/10/15 Javascript
最全面的百度地图JavaScript离线版开发
2016/09/10 Javascript
js从数组中删除指定值(不是指定位置)的元素实现代码
2016/09/13 Javascript
jquery获取easyui日期控件的值实现方法
2016/11/09 Javascript
Vue.js 2.0中select级联下拉框实例
2017/03/06 Javascript
详解windows下vue-cli及webpack 构建网站(二)导入bootstrap样式
2017/06/17 Javascript
详解Angular 自定义结构指令
2017/06/21 Javascript
细说webpack源码之compile流程-入口函数run
2017/12/26 Javascript
深入理解js 中async 函数的含义和用法
2018/05/13 Javascript
vue-router重定向不刷新问题的解决
2018/06/25 Javascript
Vue 页面状态保持页面间数据传输的一种方法(推荐)
2018/11/01 Javascript
基于jsbarcode 生成条形码并将生成的条码保存至本地+源码
2020/04/27 Javascript
JavaScript十大取整方法实例教程
2020/12/03 Javascript
[01:00:14]2018DOTA2亚洲邀请赛 4.6 淘汰赛 VP vs TNC 第三场
2018/04/10 DOTA
基于Python实现迪杰斯特拉和弗洛伊德算法
2020/05/27 Python
Pandas读取并修改excel的示例代码
2019/02/17 Python
python基于socket实现的UDP及TCP通讯功能示例
2019/11/01 Python
django 前端页面如何实现显示前N条数据
2020/03/16 Python
意大利在线购买隐形眼镜网站:VisionDirect.it
2019/03/18 全球购物
ABOUT YOU罗马尼亚:超过600个时尚品牌
2019/09/19 全球购物
行政部工作岗位职责范本
2014/03/05 职场文书
日语系毕业求职信
2014/07/27 职场文书
年底个人总结范文
2015/03/10 职场文书
酒店人事专员岗位职责
2015/04/07 职场文书
酒店工程部经理岗位职责
2015/04/09 职场文书
2015年员工试用期工作总结
2015/05/28 职场文书
七年级写作指导之游记作文
2019/10/07 职场文书