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

如何收集超类继承链中所有类关联的Items集合?

问题背景

假设有一个类继承层级结构,每个类都有一个类级别的专属Items列表,示例代码如下:

class Thing:
    Items = ['Exist']

class Being(Thing):
    Items = ['Live', 'Die']

class Human(Being):
    Items = ['Read', 'Write']

需要定义一个GetAllItems()方法,调用该方法时能返回当前类及其所有超类的Items集合,预期效果如下:

Thing.GetAllItems() # ==> ['Exist']
Being.GetAllItems() # ==> ['Live', 'Die', 'Exist']
Human.GetAllItems() # ==> ['Read', 'Write', 'Live', 'Die', 'Exist']

该方法不一定是静态方法,但目标集合本质是类级属性。

已尝试方案

最初尝试编写递归函数,但未能成功适配所有子类:

class A:  
    Items = [A1, A2, A3]

    def GetAllItems():   # 不确定如何实现为静态方法
        return getattr(type(self),'Items') + super().GetAllItems()

后来通过为每个类定义不同的Items变量并实现专属GetAllItems()方法实现需求,但需要重复编写代码,不够优雅:

class A:
    ItemsA = [A1, A2, A3]

    def GetAllItems():
        return A.ItemsA  # 根类方法

class B(A):
    ItemsB = [B1, B2, B3]

    def GetAllItems():
        return B.ItemsB + super().GetAllItems()  

class C(B):
    ItemsC = [C1, C2, C3]

    def GetAllItems():
        return C.ItemsC + super().GetAllItems()

更新方案

分享一个适用于单继承场景的可行方案:

class Thing:
    Items = ['Exist']

    @classmethod
    def GetAllItems(cls):
        return cls.Items

class Being(Thing):
    Items = ['Live', 'Die']    

    @classmethod
    def GetAllItems(cls):
        return cls.Items + cls.__base__.GetAllItems()

该方案下,所有继承自Being的子类无需额外实现GetAllItems()方法。若涉及多继承,建议基于cls.mro()实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 10:08:26