python学习笔记 使用@property
2016-11-07 14:02
375 查看
Python内置的
注意到这个神奇的
还可以定义只读属性,只定义getter方法,不定义setter方法就是一个只读属性:
上面的
@property装饰器就是负责把一个方法变成属性调用的:
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方法变成属性赋值,于是,我们就拥有一个可控的属性操作:
>>> s = Student() >>> s.score = 60 # OK,实际转化为s.set_score(60) >>> s.score # OK,实际转化为s.get_score() 60 >>> s.score = 9999 Traceback (most recent call last): ... ValueError: score must between 0 ~ 100!
注意到这个神奇的
@property,我们在对实例属性操作的时候,就知道该属性很可能不是直接暴露的,而是通过getter和setter方法来实现的。
还可以定义只读属性,只定义getter方法,不定义setter方法就是一个只读属性:
class Student(object): @property def birth(self): return self._birth @birth.setter def birth(self, value): self._birth = value @property def age(self): return 2014 - self._birth
上面的
birth是可读写属性,而
age就是一个只读属性,因为
age可以根据
birth和当前时间计算出来。
相关文章推荐
- 【Python】学习笔记——-8.2、面向对象高级编程:2.使用@property
- 初学Python的学习笔记9----面向对象编程(获取对象信息、实例属性和类属性)、面向对象高级编程(使用__slots__、使用@property)
- python学习笔记:字典的使用示例详解
- python Django 学习笔记(四)—— 使用MySQL数据库
- python 学习笔记 11 -- 使用参数使你的程序变得更性感
- python学习笔记--循环使用
- Python 学习笔记【使用元组的注意点】
- python学习笔记之--os.walk使用
- Python 学习笔记(三) 使用字符串
- Python学习笔记之疑问10:如何使用分隔符连接list中的字符串
- python学习笔记:字典的使用示例详解
- python学习笔记+使用技巧
- SVM学习笔记(2)LIBSVM在python下的使用
- Python3.x学习笔记[2.5]灵活使用urllib与re
- mongoDB学习笔记3--python下使用
- linux 学习笔记 (3) —— 使用python
- python学习笔记:datetime使用小结
- Python学习笔记—PyQuery库的使用总结
- Python ORM框架SQLAlchemy学习笔记之映射类使用实例和Session会话介绍
- Python学习笔记-字典使用