【问题标题】:How do I override a method from within an inherited method in Python如何从 Python 中的继承方法中覆盖方法
【发布时间】:2021-12-06 12:40:11
【问题描述】:

我对类继承比较陌生,需要一些帮助

我有一个问题,我想在从另一个继承的父类方法调用父类方法之后覆盖它。

基本概念如下所示:

class Parent:

    """Parent class, that defines the logical workflow"""

    def __init__(self):
        pass

    def outer_method(self):
        # This method is called from the sub_classes
        # everything in here is the same for all sub_classes
        self.__inner_method(self)

    def __inner_method(self):
        # This method is called from self.outer_method()
        # Everything in here will be handled differently by each sub_class
        # And will therefore be overridden
        pass

class Child(Parent):

    """Sub_class, that inherits from the Parent class"""

    def __init__(self):
        super().__init__()

    def __inner_method(self):
        # this should override Parent.__inner_method()
        super().__inner_method()
        print('Do some custom operations unique to this Sub_class')

这里的想法是,Child 类调用outer_method,然后调用__inner_method,我想被子类覆盖。

但这不起作用。 当我运行这个脚本时,

def main():
    MyChild = Child()
    MyChild.outer_method()

if __name__ == "__main__":
    main()

会发生什么,而不是调用Child.__inner_method(),而是调用Parent.__inner_method()

从继承的外部方法调用子类后,如何让子类覆盖父类的内部方法?

【问题讨论】:

    标签: python-3.x class oop inheritance overriding


    【解决方案1】:

    问题的原因是你选择的名字,如果一个类的名字以__开头但不以此为结尾,python会对类成员进行特殊处理,称为name mangling,这样做的原因是为了获得私有变量/方法的python版本,所以你的__inner_method被重命名为_Parent__inner_method,任何对父类的__inner_method的调用都被修改为调用这个重命名的方法,因为子类也会发生同样的情况,它的结尾是它自己的_Child__inner_method,如果不需要的话,这当然会破坏继承机制。

    解决方法很简单,将所有__inner_method重命名为_inner_method

    当您不想修改名称时,单个_ 是私有内容的约定,而__ 是当您希望它更加私密时...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-27
      • 2012-10-15
      • 2019-05-03
      • 2012-11-20
      • 1970-01-01
      • 2021-11-30
      相关资源
      最近更新 更多