python @property

来源:互联网 发布:朗文英语词典知乎 编辑:程序博客网 时间:2024/06/03 14:21

有时候我们需要对类属性的值进行一些限制,例如人的身高要大于0


此时,符合 Python 风格的做法是,把数据属性换成特性。

class Person:    def __init__(self, height):        self.height = height# 初始化赋值给特性    @property# 装饰读值方法    def height(self):# 特性方法与名称一样        return self._height# 真正存身高的变量    @height.setter# 读值方法修饰器    def height(self, value):# 读值方法要与特性名称一直        if value > 0:            self._height = value# 身高 > 0         else:            raise Exception('height muste > 0')    @height.deleter# 删除特性操作修饰器    def height(self):        self._height = 0>>> p = Person(-180)Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "<stdin>", line 3, in __init__  File "<stdin>", line 12, in heightException: height muste > 0>>> p = Person(180)>>> p.height180>>> del p.height>>> p.height0