用Python中的dataclass方法定义属性

2024-09-30 20:34:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用于边界框坐标的类,我想将其转换为dataclass,但我无法像在普通类中一样,使用类方法设置属性。这是普通班:

class BBoxCoords:
    """Class for bounding box coordinates"""
    def __init__(self, top_left_x: float, top_left_y: float, bottom_right_x: float, bottom_right_y: float):
        self.top_left_x = top_left_x
        self.top_left_y = top_left_y
        self.bottom_right_x = bottom_right_x
        self.bottom_right_y = bottom_right_y
        self.height = self.get_height()

    def get_height(self) -> float:
        return self.bottom_right_y - self.top_left_y

下面是我想要它做的:

bb = BBoxCoords(1, 1, 5, 5)
bb.height
> 4

这正是我想要的。我试着用数据类做同样的事情

from dataclasses import dataclass    

@dataclass
class BBoxCoords:
    """Class for bounding box coordinates"""
top_left_x: float
top_left_y: float
bottom_right_x: float
bottom_right_y: float
height = self.get_height()

def get_height(self) -> float:
    return self.bottom_right_y - self.top_left_y

但是self在我尝试使用它时没有定义,所以我得到了一个NameError。使用数据类执行此操作的正确方法是什么?我知道我能做到

bb = BBoxCoords(1, 1, 5, 5)
bb.get_height()
> 4

但是我宁愿调用属性而不是方法


Tags: 方法selfrightget属性topdeffloat
1条回答
网友
1楼 · 发布于 2024-09-30 20:34:13

对于这类事情,您需要__post_init__,它将在__init__之后运行。另外,请确保在__init__中未设置height,以便:

from dataclasses import dataclass, field   

@dataclass
class BBoxCoords:
    """Class for bounding box coordinates"""
    top_left_x: float
    top_left_y: float
    bottom_right_x: float
    bottom_right_y: float
    height: float = field(init=False)

    def __post_init__(self):
        self.height = self.get_height()

    def get_height(self) -> float:
        return self.bottom_right_y - self.top_left_y

在行动中:

In [1]: from dataclasses import dataclass, field
   ...:
   ...: @dataclass
   ...: class BBoxCoords:
   ...:     """Class for bounding box coordinates"""
   ...:     top_left_x: float
   ...:     top_left_y: float
   ...:     bottom_right_x: float
   ...:     bottom_right_y: float
   ...:     height: float = field(init=False)
   ...:
   ...:     def __post_init__(self):
   ...:         self.height = self.get_height()
   ...:
   ...:     def get_height(self) -> float:
   ...:         return self.bottom_right_y - self.top_left_y
   ...:

In [2]: BBoxCoords(1, 1, 5, 5)
Out[2]: BBoxCoords(top_left_x=1, top_left_y=1, bottom_right_x=5, bottom_right_y=5, height=4)

相关问题 更多 >