为什么在具有多重继承的 super() 时不能调用所有 __init__?

Why can't call all __init__ when super() with Multiple Inheritance?

显示代码:

class state():
    def __init__(self):
        print('in the state class')
        self.state = "main state"

class event():
    def __init__(self):
        print("in the event class")
        self.event = "main event"

class happystate(state,event):
    def __init__(self):
        print('in the happy state class')
        super(state,self).__init__()
        super(event,self).__init__()

happystate有两个基数class--stateevent,初始化happystate.

a = happystate()
in the happy state class
in the event class

为什么不能调用状态 class?

如果您不在其他 类 中使用 super().__init__(),并且您有多重继承,python 将停止 运行 其他 __init__ 方法。

class state():
    def __init__(self):
        super().__init__()
        print('in the state class')
        self.state = "main state"

class event():
    def __init__(self):
        super().__init__()
        print("in the event class")
        self.event = "main event"

class happystate(state,event):
    def __init__(self):
        print('in the happy state class')
        super().__init__()

我正在添加一些参考资料:

  1. From Raymond Hettinger
  2. Whosebug

正如 MisterMiyagi 所说,super(state,self).init 并不意味着“init on the super class这是状态”,意思是“init on the super class which is in self's mro after state”。

我们可以删除class stateevent中的所有super().__init__(),方法如下:

class state():
    def __init__(self):
        print('in the state class')
        self.state = "main state"

class event():
    def __init__(self):
        print("in the event class")
        self.event = "main event"

class happystate(state,event):
    def __init__(self):
        print('in the happy state class')
        super(happystate,self).__init__()
        super(state,self).__init__()

初始化 class happystate:

>>> x = happystate()
in the happy state class
in the state class
in the event class
>>> x.state
'main state'
>>> x.event
'main event'