【发布时间】: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