Python dataclass子类识别继承属性及实现自有属性返回方法
问题1解答:可以识别继承自父类的属性
Python dataclasses 模块提供了内置的字段反射能力,不需要手动解析类定义就能区分继承字段和子类自有字段:
- 调用
fields()函数可以拿到指定dataclass的所有字段元组,每个字段对象的name属性就是属性名 - 父类的字段集合和子类的字段集合做差集,就能得到子类新增的自有字段,交集就是继承自父类的字段
示例代码:
from dataclasses import fields # 父类Line的所有字段 parent_fields = {f.name for f in fields(Line)} # 子类Rectangle的所有字段 all_fields = {f.name for f in fields(Rectangle)} # 继承的字段 inherited_fields = parent_fields & all_fields # 输出为 {'x', 'length', 'color'} # 子类自有字段 child_only_fields = all_fields - parent_fields # 输出为 {'y', 'height', 'fill'}
问题2解答:实现无需硬编码的get_dict方法
核心思路是利用上面的字段反射能力,在方法内自动过滤出子类自有字段,再取值组装成字典,后续子类新增字段也能自动适配,不需要修改方法逻辑。
完整实现代码如下:
from dataclasses import dataclass, fields @dataclass class Line: x: int length: int color: str @dataclass class Rectangle(Line): y: int height: int fill: bool def get_dict(self): """ return only y, height, and fill """ # 获取直接父类的所有字段名 parent_field_names = {f.name for f in fields(self.__class__.__bases__[0])} # 过滤出当前子类独有的字段名 child_field_names = [f.name for f in fields(self) if f.name not in parent_field_names] # 组装成字典返回 return {field: getattr(self, field) for field in child_field_names}
测试效果:
r = Rectangle(x=10, length=20, color="blue", y=30, height=40, fill=True) print(r.get_dict()) # 输出:{'y': 30, 'height': 40, 'fill': True}
如果不需要适配后续子类修改的场景,也可以直接写简单的过滤规则:
def get_dict(self): return {k:v for k,v in self.__dict__.items() if k in ('y', 'height', 'fill')}
内容的提问来源于stack exchange,提问作者Tim
相关产品推荐
相关产品推荐

