Python 数据类中的自定义默认 getter 和 setter
我有一个 python 数据类,由于底层存储数据格式,它将标量存储为大小为 1 的数组,将向量存储为更大的数组。因此,对于每个成员,数据类都会实现适当的 setter 和 getter,例如:
@dataclass
class A():
_scalar: np.ndarray = np.zeros(1, np.uint32)
_vector: CustomVector("unsigned short") = CustomVector("unsigned short")
@property
def scalar(self):
return self._scalar
@scalar.setter
def scalar(self, val: np.uint16) -> None:
self._scalar[0] = val
@property
def vector(self):
return self._vector
@vector.setter
def vector(self, value):
# Clear the vector before setting
self._vector.clear()
self._vector += value
当然,我还有许多其他属性,主要是这两种标量和向量类型。我的代码最终主要是 getter 和 setter,它们的区别仅在于装饰器中和方法内部的变量名称。我想知道,Python 中是否有一种方法可以自动使用默认的 getter 和 setter?比如:
@dataclass
class A():
@use_scalar_gettersetter
_scalar: np.ndarray = np.zeros(1, np.uint32)
@use_vector_gettersetter
_vector: CustomVector("unsigned short") = CustomVector("unsigned short")
这将使代码更具可读性...感谢您的任何建议!
I have a python dataclass, which, due to underlying storage data format, stores scalars as arrays of size 1, and vectors as bigger arrays. Thus for each member the dataclass implements an appropriate setter and getter, like:
@dataclass
class A():
_scalar: np.ndarray = np.zeros(1, np.uint32)
_vector: CustomVector("unsigned short") = CustomVector("unsigned short")
@property
def scalar(self):
return self._scalar
@scalar.setter
def scalar(self, val: np.uint16) -> None:
self._scalar[0] = val
@property
def vector(self):
return self._vector
@vector.setter
def vector(self, value):
# Clear the vector before setting
self._vector.clear()
self._vector += value
Of course, I have many other properties mainly of those two scalar and vector types. My code ends up being mainly getters and setters, which differ only in the variable name in the decorator and inside the method. I wonder, if there is a way in Python to make a default getter and setter, that would automatically be used? Something like:
@dataclass
class A():
@use_scalar_gettersetter
_scalar: np.ndarray = np.zeros(1, np.uint32)
@use_vector_gettersetter
_vector: CustomVector("unsigned short") = CustomVector("unsigned short")
Which would make the code much more readable... Thanks for any advice!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论