简体   繁体   English

在父类中调用重写的父类方法

[英]Calling overridden parent class method in parent class

I'm trying to override two parent class functions train and eval in a ChildClass . 我试图在ChildClass覆盖两个父类函数traineval In the parent class, eval() basically calls train() . 在父类中, eval()基本上调用train() However, I realize that when I write my code as below, eval() in the parent class is trying to call the function train() in ChildClass - I would like eval() in the parent class to call train() in the parent class instead. 但是,我意识到当我编写如下代码时, 父类中的eval()试图在ChildClass调用函数train() - 我希望父类中的eval()在父类中调用train()而是改为。

I'm just wondering if there is any clean solutions to make changes to ChildClass that would allow the parent class to call the parent train() function? 我只是想知道是否有任何干净的解决方案来改变ChildClass ,允许父类调用父train()函数?

class ChildClass(nn.Module):
    def __init__(self):
        super(ChildClass, self).__init__()

    def train(self):
        super(ChildClass, self).train()

    def eval(self):
        super(ChildClass, self).eval()

Parent class is in a Python Package ( pytorch ), so no changes should be made: 父类位于Python包( pytorch )中,因此不应进行任何更改:

class Module(object):
    #...

    def train(self, mode=True):
        # ...
        return self

    def eval(self):
        return self.train(False)

Your overridden methods are not doing anything except invoking the parent (at least from the code you have shared). 除了调用父级(至少从您共享的代码中)之外,重写的方法没有做任何事情。

So, I think you want to have a method that has the same steps as in train()/eval(). 所以,我认为你想要一个方法与train()/ eval()中的步骤相同。 I guess you don't need to override train() or eval(), instead add method(s) in your child class and call parent train()/eval() in whichever order you want to mix them. 我猜你不需要覆盖train()或eval(),而是在你的子类中添加方法,并以你想要混合它们的顺序调用parent train()/ eval()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM