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?

1
  • 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". Commented Oct 1, 2021 at 13:28

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

-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'

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.