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

未重写子类classmethod时,如何调用父类classmethod?

解决子类调用类方法时的降级父类调用问题

问题原因

当ChildWithoutImplementation调用echo方法时,cls指向的是ChildWithoutImplementation类。此时在Parent.echo中执行super().echo(),Python会按照**方法解析顺序(MRO)**查找ChildWithoutImplementation的父类链中Parent之后的类(也就是object),但object没有定义echo方法,因此抛出AttributeError。

解决方案

方案一:显式调用父类的echo方法

直接在判断分支里调用Parent.echo,并传入Parent类本身,跳过MRO查找,强制执行父类的逻辑:

class Parent(object):
    var = "Parent"

    @classmethod
    def echo(cls):
        if cls.var is not None:
            print(f"Echoing {cls.var}")
        else:
            # 直接调用Parent的echo方法,使用Parent类作为参数
            Parent.echo(Parent)

class ChildWithImplementation(Parent):
    var = "Child 1"

class ChildWithoutImplementation(Parent):
    var = None

p = Parent()
p.echo()  # 输出:Echoing Parent
c1 = ChildWithImplementation()
c1.echo()  # 输出:Echoing Child 1
c2 = ChildWithoutImplementation()
c2.echo()  # 输出:Echoing Parent

方案二:直接使用父类变量替代无效值

如果只是需要使用父类的var值,不需要完整复用父类方法逻辑,可以直接替换变量值后输出:

class Parent(object):
    var = "Parent"

    @classmethod
    def echo(cls):
        # 若当前类的var为None,直接使用Parent的var
        target_var = cls.var if cls.var is not None else Parent.var
        print(f"Echoing {target_var}")

class ChildWithImplementation(Parent):
    var = "Child 1"

class ChildWithoutImplementation(Parent):
    var = None

# 测试结果与方案一一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 22:32:24