python - 在 Python 中使用数据类方法定义属性
问题描述
我有一个用于边界框坐标的类,我想将其转换为数据类,但我不知道如何像在普通类中那样使用类方法设置属性。这是普通的类:
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
但我宁愿调用属性而不是方法。
解决方案
对于这种事情,您需要__post_init__
,它将在之后__init__
运行。另外,请确保height
未设置在 中__init__
,因此:
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)
推荐阅读
- rx-java - 如何在 RxJava 中制作冷单“热”
- apache-spark - 如何在 Kubernetes 容器/pod 上挂载 S3 存储桶?
- wpf - WPF BindingOperations.EnableCollectionSynchronization + ObservableCollection + Reentrancy
- c# - 在 Web 应用程序和 API 之间设置 Kerberos 2 跃点身份验证
- javascript - 执行一些代码后如何调用promise?
- hadoop - 如何解释 Hadoop Grep 命令输出
- javascript - PimCore 与 VueJS 和 VueJS-Router
- c# - ContentView Xamarin 表单
- asp.net - 在 window.open 之后重定向到另一个页面
- c++ - 具有固定大小数组成员的结构的 C++ 大括号初始化