我有 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物件,是否可以確定哪些屬性是從父資料類繼承的?
例如,如何get_dict()在Rectangle不顯式輸入所有變數及其值的情況下實作該方法?
uj5u.com熱心網友回復:
請注意,資料類有一個asdict輔助函式,可用于將資料類序列化為dict物件;但是,這也包括來自超類的欄位Line,例如,所以這可能不是您想要的。
我建議查看其他屬性,例如Rectangle.__annotations__應該只包含 class 獨有的 dataclass 欄位串列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}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/345011.html
標籤:蟒蛇-3.x 遗产 python-数据类
