How do derived class constructors work in python?

devoured elysium picture devoured elysium · Dec 12, 2009 · Viewed 29.5k times · Source

I have the following base class:

class NeuralNetworkBase:
    def __init__(self, numberOfInputs, numberOfHiddenNeurons, numberOfOutputs):
        self.inputLayer = numpy.zeros(shape = (numberOfInputs))
        self.hiddenLayer = numpy.zeros(shape = (numberOfHiddenNeurons))
        self.outputLayer = numpy.zeros(shape = (numberOfOutputs))

        self.hiddenLayerWeights = numpy.zeros(shape = (numberOfInputs, numberOfHiddenNeurons))
        self.outputLayerWeights = numpy.zeros(shape = (numberOfHiddenNeurons, numberOfOutputs))

now, I have a derived class with the following code:

class NeuralNetworkBackPropagation(NeuralNetworkBase):
    def __init__(self, numberOfInputs, numberOfHiddenNeurons, numberOfOutputs):
        self.outputLayerDeltas = numpy.zeros(shape = (numberOfOutputs))
        self.hiddenLayerDeltas = numpy.zeros(shape = (numberOfHiddenNeurons))

But when I instantiate NeuralNetworkBackPropagation I'd like that both constructors get called.This is, I don't want to override the base class' constructor. Does python call by default the base class constructor's when running the derived class' one? Do I have to implicitly do it inside the derived class constructor?

Answer

ShZ picture ShZ · Dec 12, 2009

Does python call by default the base class constructor's when running the derived class' one? Do I have to implicitly do it inside the derived class constructor?

No and yes.

This is consistent with the way Python handles other overridden methods - you have to explicitly call any method from the base class that's been overridden if you want that functionality to be used in the inherited class.

Your constructor should look something like this:

def __init__(self, numberOfInputs, numberOfHiddenNeurons, numberOfOutputs):
    NeuralNetworkBase.__init__(self, numberOfInputers, numberOfHiddenNeurons, numberOfOutputs)
    self.outputLayerDeltas = numpy.zeros(shape = (numberOfOutputs))
    self.hiddenLayerDeltas = numpy.zeros(shape = (numberOfHiddenNeurons))

Alternatively, you could use Python's super function to achieve the same thing, but you need to be careful when using it.