python - 关于如何在 python 中使用属性功能的真实示例?

我对如何在 Python 中使用 @property 很感兴趣。我已经阅读了 python 文档和那里的示例,在我看来,这只是一个玩具代码:

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

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

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

    @x.deleter
    def x(self):
        del self._x

我不知道包装填充有属性装饰器的 _x 可以获得什么好处。为什么不直接实现:

class C(object):
    def __init__(self):
        self.x = None

我认为,属性功能在某些情况下可能很有用。但当?有人可以给我一些真实的例子吗?

最佳答案

其他示例包括验证/过滤设置的属性(强制它们在界限内或可接受的范围内)以及对复杂或快速变化的术语进行惰性求值。

隐藏在属性后面的复杂计算:

class PDB_Calculator(object):
    ...
    @property
    def protein_folding_angle(self):
        # number crunching, remote server calls, etc
        # all results in an angle set in 'some_angle'
        # It could also reference a cache, remote or otherwise,
        # that holds the latest value for this angle
        return some_angle

>>> f = PDB_Calculator()
>>> angle = f.protein_folding_angle
>>> angle
44.33276

验证:

class Pedometer(object)
    ...
    @property
    def stride_length(self):
        return self._stride_length

    @stride_length.setter
    def stride_length(self, value):
        if value > 10:
            raise ValueError("This pedometer is based on the human stride - a stride length above 10m is not supported")
        else:
            self._stride_length = value

https://stackoverflow.com/questions/6304040/

相关文章:

python - 如何使用列表中的键和默认为零的值创建字典?

linux - 重新加载 Flash 17 次会导致错误 #2046 并需要重新启动浏览器

linux - 如何为输出添加行号,提示行,然后根据输入进行操作?

python - 用python练习BDD

python - Python 3.3+ 中的包不需要 __init__.py

python - 不区分大小写 'in'

python - set() 是如何实现的?

linux - 有没有办法检查是否有指向目录的符号链接(symbolic link)?

linux - 如何在 Unix 系统上编辑二进制文件

linux - ELF文件格式中的section和segment有什么区别