python3 property详解

定义
一个可以使实例方法用起来像实例属性一样的特殊关键字,可以对应于某个方法,通过使用property属性,能够简化调用者在获取数据的流程(使代码更加简明)
实现property属性的两种方式

  • 类属性
    当使用类属性的方式创建property属性时,property()方法有四个参数:
    • 第一个参数是方法名,调用 对象.属性 时自动触发执行方法
    • 第二个参数是方法名,调用 对象.属性 = XXX 时自动触发执行方法
    • 第三个参数是方法名,调用 del 对象.属性 时自动触发执行方法
    • 第四个参数是字符串,调用 对象.属性.doc ,此参数是该属性的描述信息
class Student: def __init__(self): self._name = 'renwoxing'def get_name(self): return self._namedef set_name(self, name): self._name = namedef del_name(self): del self._namestu = property(get_name, set_name, del_name, 'good studeng')

  • 装饰器
    新式类中的属性有三种访问方式,如下:
    • @property对应读取
    • @方法名.setter修改
    • @方法名.deleter删除属性
class Student: def __init__(self): self._score = 0 self._name = 'renwoxing'@property def score(self): return self._score@score.setter def score(self, score): if not isinstance(score, int): raise ValueError('Score 必须是int类型') if score < 0 or score > 100: raise ValueError('Score值必须在0=

【python3 property详解】** 注意**:
不要score写成公有的属性,应该写成_score,否则object.score会使得函数名和变量名同名,self._score就可以避免递归错误。

    推荐阅读