1

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?

showkey
  • 482
  • 42
  • 140
  • 295
  • 2
    That's not how ``super`` works. ``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``*". – MisterMiyagi Oct 01 '21 at 13:28

2 Answers2

3

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
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Peter Trcka
  • 1,279
  • 1
  • 16
  • 21
-1

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'
showkey
  • 482
  • 42
  • 140
  • 295
  • 1
    This is really bad. You should never do this. Read the article from Raymond. Issue with this solution is, that you cannot more extend your code. For example if your code become more complex and `state` or `event` will have to inherit from some king of `base` class, it won't be working anymore. – Peter Trcka Oct 01 '21 at 16:09