Search code examples
pythonoopsuperclass

Should __init__() call the parent class's __init__()?


I'm used that in Objective-C I've got this construct:

- (void)init {
    if (self = [super init]) {
        // init class
    }
    return self;
}

Should Python also call the parent class's implementation for __init__?

class NewClass(SomeOtherClass):
    def __init__(self):
        SomeOtherClass.__init__(self)
        # init class

Is this also true/false for __new__() and __del__()?

Edit: There's a very similar question: Inheritance and Overriding __init__ in Python


Solution

  • In Python, calling the super-class' __init__ is optional. If you call it, it is then also optional whether to use the super identifier, or whether to explicitly name the super class:

    object.__init__(self)
    

    In case of object, calling the super method is not strictly necessary, since the super method is empty. Same for __del__.

    On the other hand, for __new__, you should indeed call the super method, and use its return as the newly-created object - unless you explicitly want to return something different.