VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > python3 >
  • python3教程之python类中super()和__init__()的区别

本站最新发布   Python从入门到精通|Python基础教程
试听地址  
https://www.xin3721.com/eschool/python.html


最近有同学问我关于Python类中的super()和__init__()共同点和不同点的问题, 我今天把它们两个的异同点总结了一下,希望可以帮助遇到同样困惑的同学。

 

单继承时super()和__init__()实现的功能是类似的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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()
= childA()
= childB()

输出结果:

1
2
3
Base create
creat A  Base create
creat B  Base create

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

 

super()只能用于新式类中

 

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

1
2
3
class Base():
    def __init__(self):
        print 'Base create'

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

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

 

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

 

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

1
2
3
def super(class_name, self):
    mro = self.__class__.mro()
    return mro[mro.index(class_name) + 1]
相关教程