Python sub Dataclass 识别继承的属性
Python sub Dataclass identify inherited attributes
我有 2 个数据class,如下所示:
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
对象,是否可以识别哪些属性是从父数据继承的class?
例如,如何在 Rectangle
中实现 get_dict()
方法而不显式输入所有变量及其值?
请注意,dataclasses 有一个 asdict
辅助函数,可用于将 dataclass 序列化为 dict
对象;但是,这还包括来自 superclass 的字段,例如 Line
,所以这可能不是您想要的。
我建议查看其他属性,例如 Rectangle.__annotations__
,它应该只有一个数据 class 字段列表,这些字段是 class 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())
只应 return Rectangle
独有的字段:
{'y': 4, 'height': 5, 'fill': 6}
我有 2 个数据class,如下所示:
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
对象,是否可以识别哪些属性是从父数据继承的class?
例如,如何在 Rectangle
中实现 get_dict()
方法而不显式输入所有变量及其值?
请注意,dataclasses 有一个 asdict
辅助函数,可用于将 dataclass 序列化为 dict
对象;但是,这还包括来自 superclass 的字段,例如 Line
,所以这可能不是您想要的。
我建议查看其他属性,例如 Rectangle.__annotations__
,它应该只有一个数据 class 字段列表,这些字段是 class 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())
只应 return Rectangle
独有的字段:
{'y': 4, 'height': 5, 'fill': 6}