【问题标题】:python inheritance and super keywordpython继承和super关键字
【发布时间】:2025-12-31 14:50:16
【问题描述】:

我无法理解这段代码 sn-p。

class First():  
  def __init__(self):  
    super(First, self).__init__()  
    print("first")  

class Second():  
  def __init__(self):  
    super(Second, self).__init__()  
    print("second")  

class Third(Second, First):  
  def __init__(self):  
    super(Third, self).__init__()  
    print("third")  

Third(); 

输出是:

first  
second  
third  

似乎每个构造函数都以基类First.__init__()然后Second.__init__()的相反顺序调用
super(Third, self).__init__() 这个语句是如何工作的。

【问题讨论】:

    标签: python-3.x multiple-inheritance


    【解决方案1】:

    您在打印之前调用了super(),所以是的,只有在super() 返回之后才能到达您的print() 表达式。

    您的班级方法解析顺序 (MRO) 是:

    >>> Third.__mro__
    (<class '__main__.Third'>, <class '__main__.Second'>, <class '__main__.First'>, <class 'object'>)
    

    所以创建Third() 然后结果:

    Third.__init__()
        super(Third, self).__init__()
            Second.__init__()                   # next in the MRO for Third
                super(Second, self).__init__()
                    First.__init__()            # next in the MRO for Third
                        super(First, self).__init__()
                            object.__init__()   # next in the MRO for Third
                                return
                        print("first")
                        return
                print("second")
                return
        print("third")
        return
    

    所以代码输出firstsecond,然后是third,但这些方法的调用顺序相反。

    旁注:super() is a type of object,不是关键字。 super() 只是另一种表达方式(尽管是 causes some side effects during compilation)。

    【讨论】: