子类调用父类method1时,如何强制父类调用子类重写的method2?
问题解答
首先纠正你代码里的一处小错误:父类的method1中调用self.method2时缺少括号,应该写成self.method2(),否则不会实际执行方法。
回到你的问题:当子类调用super().method1()时,父类的method1会自动调用子类重写后的method2,不需要额外强制操作。
原理说明
在Python中,实例方法的调用是基于实例的实际类型来查找的。当你创建Child类的实例后,调用method1时,虽然通过super()调用了父类的method1,但此时self指向的是Child类的实例。当父类method1里执行self.method2()时,Python会优先在Child类中查找method2,也就是你重写后的版本。
验证代码
我们可以运行修改后的代码来验证:
class Parent(): def method1(self): print("Parent method1 executed") self.method2() # 修正:添加括号 def method2(self): print("Parent method2 executed") class Child(Parent): def method1(self): super().method1() def method2(self): print("Child method2 executed") # 创建子类实例并调用method1 child = Child() child.method1()
运行结果
Parent method1 executed Child method2 executed
从结果可以看到,父类的method1确实调用了子类重写后的method2。
内容的提问来源于stack exchange,提问作者Aziz Temirkhanov
相关产品推荐
相关产品推荐

