【发布时间】:2020-05-13 04:27:01
【问题描述】:
我有一个用于边界框坐标的类,我想将其转换为数据类,但我不知道如何像在普通类中那样使用类方法设置属性。这是普通的类:
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
但我宁愿调用属性而不是方法。
【问题讨论】:
标签: python python-3.x python-dataclasses