欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Python中@property的理解和使用示例

时间:2021-03-17 09:41:56|栏目:Python代码|点击:

本文实例讲述了Python中@property的理解和使用。分享给大家供大家参考,具体如下:

重看狗书,看到对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相关内容可查看本站专题:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

上一篇:使用Python实现windows下的抓包与解析

栏    目:Python代码

下一篇:Python数据类型之List列表实例详解

本文标题:Python中@property的理解和使用示例

本文地址:http://www.codeinn.net/misctech/82676.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有