Python中如何在继承的父类方法内重写被调用的方法?
问题分析:子类重写的方法没生效?是Python名称修饰在搞鬼!
嘿,你遇到的这个问题核心在于Python的**名称修饰(Name Mangling)**机制——就是你给方法加的双下划线__搞的小动作!
当你在父类里定义__inner_method时,Python会自动把这个方法名偷偷改成_Parent__inner_method(格式是_类名__方法名),目的是避免子类意外重写父类的私有方法。而你子类里的__inner_method,会被改成_Child__inner_method。
所以父类的outer_method里调用的self.__inner_method(),实际上是在找_Parent__inner_method,和子类的_Child__inner_method完全是两个不同的方法,自然不会触发你子类的自定义逻辑。
解决方案:改用受保护方法(单下划线)
Python里用单下划线_开头的方法是「受保护方法」:它不会被名称修饰,子类可以正常重写,同时也通过约定告诉其他开发者——这是类内部使用的方法,别在外部直接调用。
这才是实现你需求的正确姿势,修改后的代码如下:
class Parent: """Parent class, that defines the logical workflow""" def __init__(self): pass def outer_method(self): # 调用受保护的_inner_method,子类可重写 self._inner_method() def _inner_method(self): # 改成单下划线的受保护方法 pass class Child(Parent): """Sub_class, that inherits from the Parent class""" def __init__(self): super().__init__() def _inner_method(self): # 正确重写父类的受保护方法 super()._inner_method() # 可选:如果需要复用父类的逻辑 print('Do some custom operations unique to this Sub_class') # 测试代码 def main(): my_child = Child() my_child.outer_method() if __name__ == "__main__": main()
运行这段代码,就会输出你预期的Do some custom operations unique to this Sub_class了。
关于双下划线的额外说明(不推荐)
如果你非要用双下划线(真心不建议,这违背了私有方法的设计初衷),只能在子类里直接重写父类被修饰后的方法名,比如:
class Child(Parent): def __init__(self): super().__init__() def _Parent__inner_method(self): # 直接重写父类被修饰后的方法名 print('Do some custom operations unique to this Sub_class')
这种写法虽然能运行,但可读性极差,而且如果父类名称修改,这里也得跟着改,维护成本很高,所以强烈推荐用单下划线的受保护方法方案。
内容的提问来源于stack exchange,提问作者py_coffee
相关产品推荐
相关产品推荐

