派生类构造函数如何在python中工作?

时间:2009-12-12 04:16:27

标签: python constructor derived-class 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))

现在,我有一个带有以下代码的派生类:

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

但是当我实例化NeuralNetworkBackPropagation时,我希望两个构造函数都被调用。这是,我不想覆盖基类的构造函数。在运行派生类'one时,python默认调用基类构造函数吗?我是否必须在派生类构造函数中隐式执行它?

2 个答案:

答案 0 :(得分:28)

  

python默认调用基数   运行时的类构造函数   派生班'一?我一定要吗   在派生的内部隐式地做   类构造函数?

不,是的。

这与Python处理其他重写方法的方式一致 - 如果您希望在继承的类中使用该功能,则必须显式调用已被覆盖的基类中的任何方法。

你的构造函数应该是这样的:

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

或者,您可以使用Python的super函数来实现相同的功能,但you need to be careful when using it

答案 1 :(得分:6)

你必须将它放在NeuralNetworkBackPropagation的__init__()方法中,即调用父类的__init__()方法(NeuralNetworkBase):

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

除非您在子类中覆盖它,否则始终会自动调用父类的构造函数。如果你在子类中覆盖它并想要调用父类的构造函数,那么你必须按照我上面的说明进行操作。