多继承下的super()指向的不一定是直接父类

你。 提交于 2020-05-08 04:19:20

常规情况

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

class A(Base):
    def __init__(self):
        super().__init__()
        print('A.__init__')

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

class C(A,B):
    def __init__(self):
        super().__init__() 
        print('C.__init__')

如果注释掉class B中的super

class B(Base):
    def __init__(self):
        # super().__init__()
        print('B.__init__')

super按照方法解析顺序(MRO)列表依次调用

在2中当注释掉B的super,显然Base.init__没有被打印出来,意味着A的super并没有调用Base中的__init,而是调用了B的__init__

super并不是代指直接父类的意思,而是指代MRO列表中的下一个类 对于你定义的每一个类,Python会计算出一个所谓的方法解析顺序(MRO)列表。 这个MRO列表就是一个简单的所有基类的线性顺序表。例如:

详细查看:https://python3-cookbook.readthedocs.io/zh_CN/latest/c08/p07_calling_method_on_parent_class.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!