Python 数据类中的自定义默认 getter 和 setter

发布于 2025-01-14 12:47:45 字数 1032 浏览 1 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文