Search code examples
python-3.xmultiple-inheritance

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


Show the code:

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 has two base class--state and event,initialize the happystate.

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

Why can't call state class?


Solution

  • If you don't use super().__init__() in other classes, and you have multiple inheritance, python stops running other __init__ methods.

    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__()
    

    I am adding some references:

    1. From Raymond Hettinger
    2. StackOverflow