【问题标题】:Python sub Dataclass identify inherited attributesPython子数据类识别继承属性
【发布时间】:2021-12-14 16:53:27
【问题描述】:

我有 2 个如下数据类:

from dataclasses import dataclass

@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 """

如果我构造一个Rectangle对象,是否可以识别出哪些属性是从父数据类继承的?

例如,如何在Rectangle 中实现get_dict() 方法而不显式输入所有变量及其值?

【问题讨论】:

    标签: python-3.x inheritance python-dataclasses


    【解决方案1】:

    请注意,dataclasses 有一个 asdict 辅助函数,可用于将数据类序列化为 dict 对象;但是,这也包括来自超类的字段,例如 Line,所以这可能不是您想要的。

    我建议查看其他属性,例如 Rectangle.__annotations__,它应该只有一个数据类字段列表,这些字段是类 Rectangle 独有的。例如:

    from dataclasses import dataclass, asdict
    from typing import Any
    
    
    @dataclass
    class Line:
        x: int
        length: int
        color: str
    
    
    @dataclass
    class Rectangle(Line):
        y: int
        height: int
        fill: bool
    
        def get_dict(self) -> dict[str, Any]:
            """ return only y, height, and fill """
            return {f: getattr(self, f) for f in self.__annotations__}
            # return asdict(self)
    
    
    print(Rectangle(1, 2, 3, 4, 5, 6).get_dict())
    

    应该只返回Rectangle独有的字段:

    {'y': 4, 'height': 5, 'fill': 6}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-11
      • 1970-01-01
      • 1970-01-01
      • 2021-05-07
      • 1970-01-01
      • 2013-09-02
      • 2016-10-17
      相关资源
      最近更新 更多