You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

子类调用父类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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 09:51:58