如何从 Python 中的继承方法中覆盖方法

How do I override a method from within an inherited method in Python

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

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

基本概念如下所示:

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 class 调用 outer_method 然后调用 __inner_method,我想被子 class.

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

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

if __name__ == "__main__":
    main()

发生的事情是调用 Child.__inner_method(),而不是调用 Parent.__inner_method()

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

问题的原因是您选择的名称,python 如果名称以 __ 开头但不以 __ 结尾,则对 class 成员应用特殊处理,称为 name mangling,这样做的原因是为了获得私有 variables/methods 的 python 版本,因此您的 __inner_method 结果重命名为 _Parent__inner_method 并且任何使用父 class 对 __inner_method 的调用都会被修改为对此重命名方法的调用,并且因为子 class 也会发生同样的情况,所以它的结尾是 _Child__inner_method如果不需要的话,它拥有当然会破坏继承机制。

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

单个 _ 是私有内容的约定,当您不希望名称混淆时,__ 用于当您希望它更加私有时,如果您愿意...