转载-对于Python中@property的理解和使用
原文链接:https://blog.csdn.net/u013205877/article/details/77804137
重看狗书,看到对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 = 9999
Traceback (most recent call last):
...
ValueError: score must between 0 ~ 100!
转载-对于Python中@property的理解和使用的更多相关文章
- 对于Python中@property的理解和使用
@property 这个我们在很多代码中都会用到,简单讲即为一个只读属性的调用 如果需要有修改权限,需要再加一个@属性名.setter 例: #!/usr/bin/env python # -*- c ...
- python 中 property 属性的讲解及应用
Python中property属性的功能是:property属性内部进行一系列的逻辑计算,最终将计算结果返回 property属性的有两种方式: 1. 装饰器 即:在方法上应用装饰器 2. 类属性 即 ...
- python 中property函数如何实现
实际上,在python中property(fget,fset,fdel,doc)函数不是一个真正的函数,他其实是拥有很多特殊方法的类. 这特殊类总的很多方法完成了property函数中的所有工作,涉及 ...
- python中@property装饰器的使用
目录 python中@property装饰器的使用 1.引出问题 2.初步改善 3.使用@property 4.解析@property 5.总结 python中@property装饰器的使用 1.引出 ...
- 【转载】python中not,and,or的优先级问题及用法
作业: >>> print(5<4 or 3)3>>> print(2>1 or 6)True>>> print(5>1 and ...
- 【转载】Python中如何高效实现两个字典合并,三种方法比较。
本文转载自:http://www.pythoner.com/13.html Python中将两个字典进行合并操作,是一个比较常见的问题.本文将介绍几种实现两个字典合并的方案,并对其进行比较. 对于这个 ...
- Python中使用@的理解
Python函数中使用@ 稍提一下的基础 fun 和fun()的区别 以一段代码为例: def fun(): print('fun') return None a = fun() #fun函数并将返回 ...
- python中property属性的介绍及其应用
Python的property属性的功能是:property属性内部进行一系列的逻辑计算,最终将计算结果返回. 使用property修饰的实例方法被调用时,可以把它当做实例属性一样 property的 ...
- 转载:Python中collections模块
转载自:Python中collections模块 目录 Python中collections模块 Counter defaultdict OrderedDict namedtuple deque Ch ...
随机推荐
- 在线word转html
http://www.docpe.com/word/word-to-html.aspx
- Spring Aop(十四)——Aop自动创建代理对象的原理
转发地址:https://www.iteye.com/blog/elim-2398725 Aop自动创建代理对象的原理 我们在使用Spring Aop时,通常Spring会自动为我们创建目标bean的 ...
- MySQL创建用户、授权、删除
1.在MySQL中创建新用户 使用具有shell访问权限的root用户登录MySQL服务器并创建名为“rahul”的新用户.下面的命令只允许从localhost系统访问用户rahul的MySQL服务器 ...
- 13 Ways Companies Do Whatsapp Marketing & Support (May 2019)
13 Ways Companies Do Whatsapp Marketing & Support (May 2019) By Iaroslav Kudritskiy We're livin ...
- Leetcode之并查集专题-765. 情侣牵手(Couples Holding Hands)
Leetcode之并查集专题-765. 情侣牵手(Couples Holding Hands) N 对情侣坐在连续排列的 2N 个座位上,想要牵到对方的手. 计算最少交换座位的次数,以便每对情侣可以并 ...
- pytest.mark.parametrize()参数化的应用一
from page.LoginPage import Loginpage import os, sys, pytest base_dir = os.path.dirname(os.path.dirna ...
- vue知识点积累
vue中 列表组件写key,起作用是什么? <ul> <li v-for="item in items" :key="item.id"> ...
- 巧用 Class Extension 隐藏属性
一般来说,Extension用来给Class增加私有属性和方法,写在 Class 的.m文件.但是Extension不是必须要写在.m文件,你可以写在任何地方,只要在 @implementation ...
- [转] Slf4j MDC机制
MDC ( Mapped Diagnostic Contexts ),线程安全的诊断日志存放容器. 可用于存放线程的全局日志信息, 通过xml配置后可以打印在日志中,用于日志记录.定位.分析 相关:h ...
- JSP和Servlet异常处理转发
<error-page> <!-- 指明异常类型. --> <exception-type>java.lang.ArrayIndexOutOfBoundsExcep ...