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

如何让Python子类复用父类properties方法,避免@property样板代码?

问题解决:子类复用父类properties()方法的正确实现

原问题中,子类调用properties()返回空字典,核心原因是父类的方法仅从**当前类的__dict__**中查找property对象,但继承自父类的property并不存在于子类的__dict__中,因此无法被收集。

修复方案:遍历类的方法解析顺序(MRO)收集所有property

修改父类的properties()方法,遍历当前类及其所有父类的MRO链,就能获取到所有继承来的属性:

class BaseClass(object):
    def __init__(self, A, B):
        self._A = A
        self._B = B
    
    @property
    def A(self):
        return self._A
    
    @A.setter
    def A(self, new_value):
        # ... Validate input ...
        self._A = new_value

    @property
    def B(self):
        return self._B

    @B.setter
    def B(self, new_value):
        # ... Validate input ...
        self._B = new_value

    def properties(self):
        props = {}
        # 遍历当前类及其所有父类的MRO链
        for cls in self.__class__.mro():
            for k, v in cls.__dict__.items():
                if isinstance(v, property) and k not in props:
                    props[k] = getattr(self, k)
        return props

子类使用示例

定义子类时无需重复父类的属性代码,直接继承即可:

class SubClass(BaseClass):
    def __init__(self, A, B, C):
        super().__init__(A, B)
        self._C = C
    
    @property
    def C(self):
        return self._C
    
    @C.setter
    def C(self, new_value):
        # ... 子类自己的验证逻辑 ...
        self._C = new_value

# 测试
obj = SubClass("a_val", "b_val", "c_val")
print(obj.properties())
# 输出: {'A': 'a_val', 'B': 'b_val', 'C': 'c_val'}

另一种简化实现(利用dir())

如果不需要严格区分类层级,也可以用dir()获取所有属性名,再逐个判断是否为property:

def properties(self):
    props = {}
    for attr_name in dir(self):
        attr = getattr(type(self), attr_name, None)
        if isinstance(attr, property):
            props[attr_name] = getattr(self, attr_name)
    return props

这种方式更简洁,同样能收集到所有继承的property属性,适合大部分场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 15:10:03