Does it matter if we call the superclass constructor in a subclass as first line?

Viewed 169

When using Java and C++ we must call the super class constructor as first line in the subclass.

Example:

public class MySubClass extends MyClass {
    public MySubClass() {
        super(); // must be first line code
        ... some code in the constructor ...
    }
}

When using Python we don't have to call the super class constructor as first line:

class MySubClass(MyClass):
    def __init__(self):
        ... some code ...
        MyClass.__init__(self)

Are there any differences in Python when calling the super class constructor as first line?

1 Answers

Sure there can be differences, but if you know what you are doing it is fine to do soever.

class MyClass:
    def __init__(self):
        self.a = 1

class MySubClass(MyClass):
    def __init__(self):
        self.a = 2    
        MyClass.__init__(self)
    

vs

class MySubClass(MyClass):
    def __init__(self):
        MyClass.__init__(self)        
        self.a = 2           

Result value in self.a will be different, but if it is intended, it may be valid code.

Related