如何通过ChildC重写ParentA的run()方法以实现指定输出?
实现ChildB与ChildC实例调用run()均执行外部新函数
我定义了ParentA、ChildB、ChildC三个类,继承关系为ChildB继承ParentA,ChildC继承ChildB。现需通过ChildC相关修改,让ChildB与ChildC的实例调用run()方法时,都执行外部导入的新run函数(输出"new method")。
原代码如下:
class ParentA: def __init__(self): pass def run(self): print("ParentA") def other(self): pass class ChildB(ParentA): def __init__(self): super().__init__() def play(self): pass class ChildC(ChildB): def __init__(self): super().__init__() # 从其他文件导入的新run函数 def run(a=1, b=2): print("new method") # 执行更多新逻辑... child_b = ChildB() child_c = ChildC() print(child_b.run()) print(child_c.run())
期望输出:
new method new method
解决方案
这里提供两种简洁的实现方式,均能满足需求:
方式一:直接修改ParentA的run方法
由于ChildB继承自ParentA且未重写run,修改ParentA的run方法会让所有子类实例自动共享新方法:
class ParentA: def __init__(self): pass def run(self): print("ParentA") def other(self): pass class ChildB(ParentA): def __init__(self): super().__init__() def play(self): pass class ChildC(ChildB): def __init__(self): super().__init__() # 从其他文件导入的新run函数 def run(a=1, b=2): print("new method") # 执行更多新逻辑... # 核心修改:替换ParentA的run方法为外部函数 ParentA.run = run child_b = ChildB() child_c = ChildC() child_b.run() child_c.run()
方式二:通过ChildC重写并同步修改ChildB
如果希望修改操作集中在ChildC相关逻辑里,可以在定义ChildC时重写run,同时修正ChildB的方法指向:
class ParentA: def __init__(self): pass def run(self): print("ParentA") def other(self): pass class ChildB(ParentA): def __init__(self): super().__init__() def play(self): pass class ChildC(ChildB): def __init__(self): super().__init__() # 重写ChildC的run方法,调用外部函数 def run(self, a=1, b=2): run(a, b) # 从其他文件导入的新run函数 def run(a=1, b=2): print("new method") # 执行更多新逻辑... # 同步修改ChildB的run方法指向外部函数 ChildB.run = run child_b = ChildB() child_c = ChildC() child_b.run() child_c.run()
两种方式都能实现目标输出:方式一更为直接,所有继承ParentA的类都会自动适配新方法;方式二则将修改集中在ChildC相关代码中,更贴合“通过ChildC重写”的需求。
内容的提问来源于stack exchange,提问作者Jiangtao Liu
相关产品推荐
相关产品推荐

