python继承和超级关键字

时间:2017-10-27 09:23:51

标签: python-3.x multiple-inheritance

我无法理解此代码段。

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__()这句话是如何起作用的。

1 个答案:

答案 0 :(得分: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)。