【转】python类中super()和__init__()的区别

单继承时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()继承时不用显式引用基类。

super()只能用于新式类中

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

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

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

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

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

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类中super()和__init__()的区别的更多相关文章

  1. python类中super()和__init__()的区别

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

  2. Python类中super()和__init__()的关系

    Python类中super()和__init__()的关系 1.单继承时super()和__init__()实现的功能是类似的 class Base(object): def __init__(sel ...

  3. 【转】python---方法解析顺序MRO(Method Resolution Order)<以及解决类中super方法>

    [转]python---方法解析顺序MRO(Method Resolution Order)<以及解决类中super方法> MRO了解: 对于支持继承的编程语言来说,其方法(属性)可能定义 ...

  4. 第7.14节 Python类中的实例方法详析

    第7.14节 Python类中的实例方法详析 一.    实例方法的定义 在本章前面章节已经介绍了类的实例方法,实例方法的定义有三种方式: 1.    类体中定义实例方法 第一种方式很简单,就是在类体 ...

  5. 第8.6节 Python类中的__new__方法深入剖析:调用父类__new__方法参数的困惑

    上节<第8.5节 Python类中的__new__方法和构造方法__init__关系深入剖析:执行顺序及参数关系案例详解>通过案例详细分析了两个方法的执行顺序,不知大家是否注意到了,在上述 ...

  6. 孤荷凌寒自学python第二十四天python类中隐藏的私有方法探秘

    孤荷凌寒自学python第二十四天python类中隐藏的私有方法探秘 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 今天发现了python的类中隐藏着一些特殊的私有方法. 这些私有方法不管我 ...

  7. Python 简明教程 --- 20,Python 类中的属性与方法

    微信公众号:码农充电站pro 个人主页:https://codeshellme.github.io 与客户保持良好的关系可以使生产率加倍. -- Larry Bernstain 目录 类中的变量称为属 ...

  8. 第7.18节 案例详解:Python类中装饰器@staticmethod定义的静态方法

    第7.18节 案例详解:Python类中装饰器@staticmethod定义的静态方法 上节介绍了Python中类的静态方法,本节将结合案例详细说明相关内容. 一.    案例说明 本节定义了类Sta ...

  9. 第8.12节 Python类中使用__dict__定义实例变量和方法

    上节介绍了使用实例的__dict__查看实例的自定义属性,其实还可以直接使用__dict__定义实例变量和实例方法. 一. 使用__dict__定义实例变量 语法: 对象名. dict[属性名] = ...

随机推荐

  1. Go GraphQL初学者教程

    Go GraphQL初学者教程 https://tutorialedge.net/golang/go-graphql-beginners-tutorial/ https://tutorialedge. ...

  2. 剑指Offer_编程题_5

    题目描述 用两个栈来实现一个队列,完成队列的Push和Pop操作. 队列中的元素为int类型.   class Solution { public: void push(int node) { if( ...

  3. python金融反欺诈-项目实战

    python信用评分卡(附代码,博主录制) https://study.163.com/course/introduction.htm?courseId=1005214003&utm_camp ...

  4. Spring Boot学习记录02_构建SpringBoot工程_通过idea构建

    1.通过idea新建工程 2.Initial Service Url指向的地址就是Spring官方提供的Spring Initializr工具地址 3.结合情况进行设置 4.这里我选择的版本是1.5. ...

  5. C++回顾day01---<const常量重点>

    一:定义常整型数 const int a;(或者int const a;)  不涉及指针 不可改变值(也不可通过指针修改) 二:定义一个指向常整型数的指针 const int* c;   可改指针指向 ...

  6. 解决CDN传统方法引入Iview icon 不显示问题

    因为需要字体文件,可以在github上下载. 将文件下载之后放到fonts文件夹下,fonts文件夹要与Iview.css在同级目录

  7. VirtualBox安装Ubuntu14.04

    创建虚拟机 点击 新建(N) 设置虚拟机的名称,类型与版本,如下图所示: 分配虚拟机的内存大小,受PC实际内存影响,暂时设置为2G,如下图所示: 分配虚拟机的硬盘大小,默认即可,如下图所示: 分配虚拟 ...

  8. js拼接HTML页面元素a标签遇到的问题

    业务,如下图需要做一个广告轮播的图片链接 使用了ajax请求后台,在js拼接html,关键代码: $("#scroll_img").html(""); for ...

  9. sqoop 使用

    spark 环境搭建 下载解压 wget https://mirrors.tuna.tsinghua.edu.cn/apache/sqoop/1.4.7/sqoop-1.4.7.bin__hadoop ...

  10. Kettle系列:Pentaho DI (Kettle) 下载地址

    Kettle 8 已经发布, 下载地址还不太好找, 这里记录一下: 注: 所有大型软件升级都需要谨慎,  尤其是大版本的第一个小版本都不推荐在生产环境使用. github 总是有最新版 https:/ ...