对于Python中@property的理解和使用
来源:互联网 发布:数学建模中的十大算法 编辑:程序博客网 时间:2024/06/06 12:24
重看狗书,看到对User表定义的时候有下面两行
@property def password(self): raise AttributeError('password is not a readable attribute') @password.setter def password(self, password): self.password_hash = generate_password_hash(password)
遂重温下这个property的使用
在我们定义数据库字段类的时候,往往需要对其中的类属性做一些限制,一般用get和set方法来写,那在python中,我们该怎么做能够少写代码,又能优雅的实现想要的限制,减少错误的发生呢,这时候就需要我们的@property闪亮登场啦,巴拉巴拉能量……..
用代码来举例子更容易理解,比如一个学生成绩表定义成这样
class Student(object): def get_score(self): return self._score def set_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
我们调用的时候需要这么调用:
>>> s = Student()>>> s.set_score(60) # ok!>>> s.get_score()60>>> s.set_score(9999)Traceback (most recent call last): ...ValueError: score must between 0 ~ 100!
但是为了方便,节省时间,我们不想写s.set_score(9999)啊,直接写s.score = 9999不是更快么,加了方法做限制不能让调用的时候变麻烦啊,@property快来帮忙….
class Student(object): @property def score(self): return self._score @score.setter def score(self,value): if not isinstance(value, int): raise ValueError('分数必须是整数才行呐') if value < 0 or value > 100: raise ValueError('分数必须0-100之间') self._score = value
看上面代码可知,把get方法变为属性只需要加上@property装饰器即可,此时@property本身又会创建另外一个装饰器@score.setter,负责把set方法变成给属性赋值,这么做完后,我们调用起来既可控又方便
>>> s = Student()>>> s.score = 60 # OK,实际转化为s.set_score(60)>>> s.score # OK,实际转化为s.get_score()60>>> s.score = 9999Traceback (most recent call last): ...ValueError: score must between 0 ~ 100!
阅读全文
0 0
- 对于Python中@property的理解和使用
- python中@property的使用
- python中property函数的理解
- Python中@property的粗略理解
- Python中对于yield的个人理解
- 对于Python中RawString的理解
- 关于python中@property的使用
- 关于python中@property的使用
- python中property的使用实例
- 对于python官方doc中相对路径重复init的理解和实验
- Android菜鸟的我对于view animator 和 property animation异同的理解
- Python中property属性(特性)的理解
- OC中对于属性的总结(@property)
- 【python】@property 的使用
- python property的使用
- 自己对于python的理解
- 对于Python中if __name__=='__main__' 的理解
- 对于C#中委托和事件的理解
- [CMake] CMake的使用
- 如何实现一个楼中楼的评论系统
- [CMake] 推荐一个关于CMake的一个很详细的教程
- jquery mobile input 和select 改变宽度
- [PTA MOOC] 自测-5 Shuffling Machine(20 分)
- 对于Python中@property的理解和使用
- H264详解之打包形式
- 并查集例题:亲戚
- 研一下学期总结
- C++11 智能指针std::shared_ptr/std::unique_ptr/std::weak_ptr
- sublime快捷键
- BZOJ2201彩色圆期望DP
- appium python-client代码分析(二)
- Flarum 源码安装错误