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

Time:10-02

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?

CodePudding user response:

If you dont 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 refferences:

  1. From Raymond Hettinger
  2. StackOverflow

CodePudding user response:

As MisterMiyagi say that super(state,self).init does not mean "init on the super class which is state", it means "init on the super class which is in self's mro after state".

We can remove all the super().__init__() in class state and event with such other way as below:

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

Initialize the 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'
  • Related