python - 在 Python 中定义未更改的公共(public)变量是一个好习惯吗?

标签 python design-patterns properties attributes setter

假设我们有一个类,在创建后的某个时刻需要为其分配一个值:

class ProcStatus:
    def __init__(self, name):
        self.name = name
        self._status_code = None

    def set_status_code(self, value):
        self._status_code = value

    def print_proc_status(self):  # Some function that does something with the status code
        print(f'{self.name} returned code {self._status_code}')


status = ProcStatus('ls')
# Some code in between
status.set_status_code(1)
status.print_proc_status()

使用这种设计,通过界面可以清楚地看出调用者可以(并且鼓励)显式设置状态代码。然而,更Pythonic的方法是使用属性:

class ProcStatus:
    def __init__(self, name):
        self.name = name
        self.status_code = None

    def print_proc_status(self):  # Some function that does something with the status code
        print(f'{self.name} returned code {self.status_code}')


status = ProcStatus('ls')
# Some code in between
status.status_code = 1
status.print_proc_status()

第二个设计是否更好,尽管看起来有点误导,因为 status_code 在类中从未更新?或者,分配给私有(private)字段的属性 setter 和 getter 是正确的方法吗?

最佳答案

为变量设置 setter 和 getter 的实用性在于,它们可以强制执行一些约束或维护用户为字段设置的值的类不变量 - 换句话说,它们允许您“清理”其他可能任意的值。

实现两全其美的最Pythonic方法(您的示例#1和#2)是使用@property装饰器,它看起来像:

class ProcStatus:
    def __init__(self, name):
        self.name = name
        self._status_code = None

    @property
    def status_code(self):
        print("Getting")
        return self._status_code

    @property.setter
    def status_code(self, value):
        print("Setting")
        # maybe apply constraints, check `value` for validity
        self._status_code = value

现在您可以享受 setter 和 getter 的额外好处以及 status.status_code = 1print(status.status_code) 的优点

关于python - 在 Python 中定义未更改的公共(public)变量是一个好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57329747/

相关文章:

python - 找不到 GraphViz 的可执行文件(python 3 和 pydotplus)

java - 如何处理复合模式中的添加、删除功能?

python - 从列表中获取相关词典

python - 如何根据 xrange() 的输出添加值?

python - 如何使用 Pandas 将巨大的 CSV 转换为 SQLite?

php - 通过引用使用 __get()

javascript - 可以向类型化数组添加属性吗?

c# - 为 "character"设计一种干净/灵活的方式来在角色扮演游戏中施放不同的法术

design-patterns - Windows服务和设计模式

c# - ASP.NET C# - 如何为 UserControl 内的 CheckBoxList 设置公共(public)属性?