is "correct" or pythonic, this way of make getters or is better to use @property?
Question:
I have a class where the attribute is a numpy array, and a lot of getters, for several slices of that array.
The question is about what is a more pythonic way of doing this
def get_right_knee(self) -> YoloV7PoseKeypoint:
return self._get_x_y_conf(49)
or
@property
def right_knee(self) -> YoloV7PoseKeypoint:
return self._get_x_y_conf(49)
the _get_x_y_conf function is:
def _get_x_y_conf(self, start_index: int) -> YoloV7PoseKeypoint:
"""
Get the x, y, and confidence values for a single keypoint.
:param start_index: The index at which to start reading values from the raw_keypoints list.
:return: A YoloV7PoseKeypoint object representing a single keypoint.
"""
end_index = start_index + self._step_keypoint
x = self.raw_keypoints[start_index:end_index][0]
y = self.raw_keypoints[start_index:end_index][1]
conf = self.raw_keypoints[start_index:end_index][2]
return YoloV7PoseKeypoint(x=x, y=y, conf=conf)
thanks
Answers:
For your case, I’d be much more tempted to use a more generic function with an Enum
or dict
from enum import Enum
class Joints(Enum):
KNEE_RIGHT = 49
class WhichHasThatJointMethods:
...
def get_joint(self, joint: Union[Joints, int]):
if isinstance(joint, Enum):
joint = joint.value
return self._get_x_y_conf(joint)
Then the usage can be
some_instance.get_joint(Joints.KNEE_RIGHT)
I have a class where the attribute is a numpy array, and a lot of getters, for several slices of that array.
The question is about what is a more pythonic way of doing this
def get_right_knee(self) -> YoloV7PoseKeypoint:
return self._get_x_y_conf(49)
or
@property
def right_knee(self) -> YoloV7PoseKeypoint:
return self._get_x_y_conf(49)
the _get_x_y_conf function is:
def _get_x_y_conf(self, start_index: int) -> YoloV7PoseKeypoint:
"""
Get the x, y, and confidence values for a single keypoint.
:param start_index: The index at which to start reading values from the raw_keypoints list.
:return: A YoloV7PoseKeypoint object representing a single keypoint.
"""
end_index = start_index + self._step_keypoint
x = self.raw_keypoints[start_index:end_index][0]
y = self.raw_keypoints[start_index:end_index][1]
conf = self.raw_keypoints[start_index:end_index][2]
return YoloV7PoseKeypoint(x=x, y=y, conf=conf)
thanks
For your case, I’d be much more tempted to use a more generic function with an Enum
or dict
from enum import Enum
class Joints(Enum):
KNEE_RIGHT = 49
class WhichHasThatJointMethods:
...
def get_joint(self, joint: Union[Joints, int]):
if isinstance(joint, Enum):
joint = joint.value
return self._get_x_y_conf(joint)
Then the usage can be
some_instance.get_joint(Joints.KNEE_RIGHT)