杨桃的Python基础教程——第8章:Python类和对象(五)多继承和super函数

本人CSDN博客专栏:https://blog.csdn.net/yty_7
Github地址:https://github.com/yot777/Python-Primary-Learning

 

8.5 多继承和super函数

super函数在之前已经出现过,作用是调用父类的方法。单继承的时候很容易理解,但多继承的时候就要注意了,特别是在“钻石继承”的时候。

Python多继承举例(使用父类类名):

class Base:
  def __init__(self):
    print('This is Base init function')
#A单继承自Base类
class A(Base):
  def __init__(self):
    Base.__init__(self)
    print('This is init function of A')
#B单继承自Base类
class B(Base):
  def __init__(self):
    Base.__init__(self)
    print('This is init function of B')
#C多继承自A类和B类
class C(A,B):
  def __init__(self):
    A.__init__(self)
    B.__init__(self)
    print('This is init function of C')
#实例化一个C类的对象c
c = C()

运行结果:
This is Base init function
This is init function of A
This is Base init function
This is init function of B
This is init function of C

Python多继承举例(使用super函数):

class Base:
  def __init__(self):
    print('This is Base init function')
#A单继承自Base类
class A(Base):
  def __init__(self):
    super().__init__()
    print('This is init function of A')
#B单继承自Base类
class B(Base):
  def __init__(self):
    super().__init__()
    print('This is init function of B')
#C多继承自A类和B类
class C(A,B):
  def __init__(self):
    super().__init__()
    print('This is init function of C')
#实例化一个C类的对象c
c = C()

运行结果:
This is Base init function
This is init function of B
This is init function of A
This is init function of C

同样是C多继承自A类和B类,为什么使用super函数运行的结果不一样?这涉及到理解PythonMRO原理(Method Resolution Order:方法解析顺序)。针对于每一个定义的类,Python都会计算出一个MRO的列表。

 

不使用super函数时,只排列到每个类的上一层父类

CABase CBBase然后反向调用方法

BaseAC BaseBCBase会调用两次)

 

使用super函数时,对所有的基类进行从左到右的遍历排列,直到找到所有类的根类为止:CABBase

不能从A类直接指向Base,否则就漏掉了B

然后反向调用方法:

BaseBACBase只调用一次)

 

参考教程:

廖雪峰的Python教程

https://www.liaoxuefeng.com/wiki/1016959663602400

廖雪峰的Java教程

https://www.liaoxuefeng.com/wiki/1252599548343744

Python3 教程 | 菜鸟教程
https://www.runoob.com/python3/
 

如果您觉得本篇本章对您有所帮助,欢迎关注、评论、点赞!Github欢迎您的Follow、Star!
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值