python - 您是否使用 get/set 模式(在 Python 中)?

标签 python getter-setter

使用 get/set 似乎是 Java 中的一种常见做法(出于各种原因),但我几乎看不到使用它的 Python 代码。

为什么在 Python 中使用或避免使用 get/set 方法?

最佳答案

在python中,你可以直接访问该属性,因为它是公共(public)的:

class MyClass:

    def __init__(self):
        self.my_attribute = 0  

my_object = MyClass()
my_object.my_attribute = 1 # etc.

如果你想对属性的访问或突变做一些事情,你可以使用properties :

class MyClass:

    def __init__(self):
        self._my_attribute = 0

    @property
    def my_attribute(self):
        # Do something if you want
        return self._my_attribute

    @my_attribute.setter
    def my_attribute(self, value):
        # Do something if you want
        self._my_attribute = value

至关重要的是,客户端代码保持不变。

关于python - 您是否使用 get/set 模式(在 Python 中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2579840/

相关文章:

java 枚举 getter setter

ios - _和 self 之间的区别。在 Objective-C 中

python - 在 python 脚本中使用 "pip install/uninstall"

python - 从二进制文件中解码 python 中的字符串列表

python - 关闭由 ConfigParser 打开的文件

Python 正则表达式替换为 ASCII 值

java - Java中getter的访问安全

javascript - TypeScript 中的自动 getter 和 setter

c++ - 方法调用返回空值

python - OpenCV 检测非常小的线条