How do derived class constructors work in python?

后端 未结 2 1978
情深已故
情深已故 2021-02-05 05:49

I have the following base class:

class NeuralNetworkBase:
    def __init__(self, numberOfInputs, numberOfHiddenNeurons, numberOfOutputs):
        self.inputLayer         


        
相关标签:
2条回答
  • 2021-02-05 06:19

    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.

    0 讨论(0)
  • 2021-02-05 06:41

    You will have to put this in the __init__() method of NeuralNetworkBackPropagation, that is to call the __init__() method of the parent class (NeuralNetworkBase):

    NeuralNetworkBase.__init__(self, numberOfInputs, numberOfHiddenNeurons, numberOfOutputs)
    

    The constructor of the parent class is always called automatically unless you overwrite it in the child class. If you overwrite it in the child class and want to call the parent's class constructor as well, then you'll have to do it as I showed above.

    0 讨论(0)
提交回复
热议问题