python中使用@property
2015-11-19 17:29
513 查看
class Student(object): @property def score(self): return self._score @score.setter def score(self, value): if not isinstance(value, int): raise ValueError('score must be an integer!') if value < 0 or value > 100: raise ValueError('score must between 0 ~ 100!') self._score = value
@property的实现比较复杂,我们先考察如何使用。把一个getter方法变成属性,只需要加上
@property就可以了,此时,
@property本身又创建了另一个装饰器
@score.setter,负责把一个setter方法变成属性赋值,于是,我们就拥有一个可控的属性操作:
转自:
http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386820062641f3bcc60a4b164f8d91df476445697b9e000
相关文章推荐
- MAC下创建python虚拟环境
- python 字典排序,列表排序详细
- python 类方法 的调用
- python 模块的创建 和使用
- Python Argparse模块的使用例子,往python脚本传参数
- Python Decorator
- Python常见命令
- Python 中 Iterator和Iterable的区别
- 王亟亟的Python学习之路(六)-递归,迭代,列表生成式
- 王亟亟的Python学习之路(六)-递归,迭代,列表生成式
- Python 主要模块和常用方法简览
- python 函数参数的传递(参数带星号的说明)
- python eventlet模块
- <the hacker guide to python>读书笔记
- python signal模块
- python 调用系统命令,执行命令行
- 使用PyCharm配合部署Python的Django框架的配置纪实
- Python的startswith与endswith函数
- 安装numpy/scipy/scikit-learn的方法
- python 通过urllib 访问api接口