python :为什么 setter和getter ?如何快速设置属性?

标签 python setter getter

<分区>

Possible Duplicate:
What is the benefit to using a ‘get function’ for a python class?

我刚开始读Python,但我想知道为什么Python根本不需要setter和getter?它已经有像属性一样的对象变量

考虑

class C(object):
    def _init_(self):
        self._x = None

    def get_x(self):
        return self._x

    def set_x(self, value):
        self._x = valu
    x = property(get_x, set_x)

我们可以只使用 C.x = "value"来做我们想做的事情吗?属性(property)的好处是什么?

顺便说一句,以这种方式创建 property/setter/getter 对我来说很麻烦,有什么办法可以简化它吗?喜欢

class C()
   has_attributes("x", "y", "z")

最佳答案

您可以使用属性来获得您想要的:

class C(object):
    def _init_(self):
        self._x = None
    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

然后您可以使用通常的属性语法访问该属性:

c = C()
c.x = 10    #calls the setter
print(c.x)  #calls the getter

使用属性而不是普通数据属性有一些原因:

  • 您可以记录该属性
  • 您可以通过将其设置为只读或检查正在设置的类型/值来控制对属性的访问
  • 您不会破坏向后兼容性:如果某个东西是一个普通的实例属性,然后您决定将其转换为一个属性,那么使用该属性的代码仍然可以工作。如果您使用显式获取/设置方法,则所有使用旧 API 的代码都必须更改
  • 它比使用明确的 get/set 方法更具可读性。

关于 python :为什么 setter和getter ?如何快速设置属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14028169/

相关文章:

ios - 使用 Picker View - setter、getter 混淆的概念

python - 以编程方式设置属性

c++ - "Value Validation in Getter/Setter"是好的样式吗?

java - 仅使用 getter 修改私有(private)类属性

javascript - Javascript 中的静态变量只设置一次

python - 将值分配给图像数组的随机 block 的有效方法?

Python:如何定义可由多处理池从命令行参数访问的全局变量?

Python pandas 使用 map 将多列添加到数据框

python - 将 Django 应用程序部署到 Azure VS2017 - 自定义 python

javascript - 如何为已定义的 JavaScript 对象定义 getter 属性?