pythonclassconvention

Python convention: should I normally call the super class' __init__?


I read the highest rated answer to this question, and it says we should call the super class' __init__ if we need to, and we don't have to. But my question is more about convention.

Should I normally, as a general rule, always call the superclass' __init__ in my class' __init__, regardless of whether or not I currently 'need' the functionality in that method?


Solution

  • Some classes need their __init__ method to be called in order to work. They use their __init__ method sets attributes that will be needed.

    Example:

    class one ():
        def __init__ (self):
            self.number = 20
        def show_number(self):
            return self.number
    

    If you inherit from the above class, you will need to call its __init__ method in order to define the attribute number. If the __init__ method is not called you could get an error when you try to call the method show_number.

    As for the syntax, if nothing happens in the __init__ method of the inherited class you don't need to call it. If you think not calling the __init__ method would confuse others, you can always explain your reasoning with comments. It does not do any harm to call it even if you don't need it.