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

Python子类中如何让父类__init__调用自身fct而非子类重写的fct?

解决方案

你的问题核心是Python的方法多态特性导致的:当父类__init__中调用self.fct()时,self实际是子类Child的实例,因此会优先调用子类重写后的fct方法,而非父类自身的。以下是两种不修改方法名的解决思路:

方法一:直接指定父类方法调用

在父类的__init__中,通过父类名直接调用自身的fct方法,并传入当前self,绕开多态查找机制:

class Parent(object):
    def __init__(self):
        Parent.fct(self)  # 明确调用父类的fct方法

    def fct(self):
        # do some basic stuff
        print("Parent's basic operation")
        
class Child(Parent):
    def __init__(self):
        super().__init__()  # 此时会执行Parent的fct
        self.fct()  # 再执行Child的fct

    def fct(self):
        # add other stuff
        print("Child's additional operation")

这种方式直接满足你的需求:super().__init__()执行父类的fct,子类__init__后续再执行自身的fct。

方法二:重构子类方法,让其主动调用父类实现

如果希望fct方法本身就包含"先父类逻辑,再子类逻辑"的语义,可以修改子类的fct,让它先调用父类的fct,再执行自己的逻辑:

class Parent(object):
    def __init__(self):
        self.fct()

    def fct(self):
        # do some basic stuff
        print("Parent's basic operation")
        
class Child(Parent):
    def __init__(self):
        super().__init__()  # 调用的是Child的fct,而它会先执行Parent的fct

    def fct(self):
        super().fct()  # 先执行父类的fct
        # add other stuff
        print("Child's additional operation")

这种方式更符合面向对象的扩展设计,子类的fct自然继承父类的逻辑并扩展,无需在__init__中重复调用两次fct。

内容的提问来源于stack exchange,提问作者Patrick

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 19:31:24