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

如何通过Python继承让子类B、C输出对应id值?

问题描述

现有如下Python类定义:

id_A = 'A'
id_B = 'B'
id_C = 'C'

class A:
    def get_id(self):
        # The expected output: id_A
        return id_A

class B(A):
...
...
    def __init__(self):
        pass

class C(A):
...
...
    def __init__(self):
        pass

需要利用继承机制,使类B和C的实例调用get_id方法时,分别输出id_B(即'B')和id_C(即'C'),要求实现如下输出结果:

a = A()
b = B()
c = C()

a.get_id() # 输出应为'A'
b.get_id() # 输出应为'B'
c.get_id() # 输出应为'C'
解决方案

方法一:利用类属性覆盖(推荐)

这种方式通过类属性的继承与覆盖实现需求,无需重复编写get_id方法,更符合面向对象的继承设计原则:

id_A = 'A'
id_B = 'B'
id_C = 'C'

class A:
    id = id_A  # 基类定义id属性
    def get_id(self):
        return self.id  # 返回当前实例所属类的id属性

class B(A):
    id = id_B  # 子类覆盖基类id属性
    def __init__(self):
        pass

class C(A):
    id = id_C  # 子类覆盖基类id属性
    def __init__(self):
        pass

方法二:子类重写get_id方法

如果不想修改基类的get_id实现,也可以直接在子类中重写该方法,返回对应的全局变量:

id_A = 'A'
id_B = 'B'
id_C = 'C'

class A:
    def get_id(self):
        return id_A

class B(A):
    def get_id(self):
        return id_B
    def __init__(self):
        pass

class C(A):
    def get_id(self):
        return id_C
    def __init__(self):
        pass

验证运行

两种方法都可以得到预期结果:

a = A()
b = B()
c = C()

print(a.get_id())  # 输出 'A'
print(b.get_id())  # 输出 'B'
print(c.get_id())  # 输出 'C'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 21:25:23