python中,我们可以直接添加和修改属性的值:

>>> class Student(object):
... pass
...
>>> s = Student()
>>> s.score = 101

但是,101明显超过了满分100分,不合理。可以通过创建setScore()方法,进行参数检查:

>>> class Student(object):
... def setScore(self,score):
... if not isinstance(score,int):
... raise ValueError('分数必须是一个整数')
... if score < 0 or score > 100:
... raise ValueError('分数值必须在0到100之间')
... self.score = score
... def getScore(self):
... return self.score
...
>>> s = Student()
>>> s.setScore(200)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in setScore
ValueError: 分数值必须在0到100之间
>>> s.setScore(99)
>>> s.getScore()
99

但是上面的过程略显复杂。

这时,可以使用@property,既可以用类似属性的方法访问类的变量,又可以检查参数,@property实现起来稍微有点复杂:

>>> class Student(object):
... @property
... def score(self):
... return self._score
... @score.setter
... def score(self,score):
... if not isinstance(score,int):
... raise ValueError('必须是整数')
... if score < 0 or score > 100:
... raise ValueError('必须在0到100之间')
... self._score = score
...
>>> s = Student()
>>> s.score = 88
>>> s.score = 55
>>> s.score = 101
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 10, in score
ValueError: 必须在0到100之间

把一个getter方法变成属性,只需要加上@property即可,同时,@property本身又创建了另外一个装饰器@score.setter,该装饰器负责把一个setter方法变成属性赋值。

另外,只定义getter方法,不定义setter方法就是在定义一个只读属性:

>>> class Student(object):
... @property
... def birth(self):
... return self._birth
... @birth.setter
... def birth(self,birth):
... self._birth = birth
... @property
... def age(self):
... return 2018 - self._birth
...
>>> s =Student()
>>> s.birth = 1991
>>> s.birth
1991
>>> s.age
27
>>> s.age = 20
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

最后一步,证明了age只是一个只读属性!

Python面向对象-@property装饰器的更多相关文章

  1. Python的property装饰器的基本用法

    Python的@property装饰器用来把一个类的方法变成类的属性调用,然后@property本身又创建了另一个装饰器,用一个方法给属性赋值.下面是在类中使用了@property后,设置类的读写属性 ...

  2. python中@property装饰器的使用

    目录 python中@property装饰器的使用 1.引出问题 2.初步改善 3.使用@property 4.解析@property 5.总结 python中@property装饰器的使用 1.引出 ...

  3. [转载]Python使用@property装饰器--getter和setter方法变成属性

    原贴:为什么Python不需要getter和setter getter 和 setter在java中被广泛使用.一个好的java编程准则为:将所有属性设置为私有的,同时为属性写getter和sette ...

  4. 【python】@property装饰器

    Python内置的@property装饰器可以把类的方法伪装成属性调用的方式.也就是本来是Foo.func()的调用方法,变成Foo.func的方式.在很多场合下,这是一种非常有用的机制. class ...

  5. Python 利用@property装饰器和property()方法将一个方法变成属性调用

    在创建实例属性时,如果直接把实例属性暴露出去,虽然写起来简单,但是存在一些风险,比如实例属性可以在外部被修改. 为了限制外部操作,可以通过一个set_score()方法来设置成绩,再通过一个get_s ...

  6. Python之property装饰器

    参考: http://www.cnblogs.com/lovemo1314/archive/2011/05/03/2035600.html http://joy2everyone.iteye.com/ ...

  7. python面向对象:组合、封装、property装饰器、多态

    一.组合二.封装三.property装饰器四.多态 一.组合 ''' 1. 什么是组合 一个对象的属性是来自于另外一个类的对象,称之为组合 2. 为何用组合 组合也是用来解决类与类代码冗余的问题 3. ...

  8. 面向对象之封装 及@property装饰器使用

    目录 封装 1.封装的定义 2.封装的目的: 3.封装的三种方式 4.封装的优点 5.访问限制(封装) @property 装饰器 属性property底层实现 封装 1.封装的定义 将复杂的丑陋的, ...

  9. python中面向对象之装饰器

    python面向对象内置装饰器property,staticmethod,classmethod的使用 @property 装饰器作用及使用 作用:面向对象中的方法伪装成属性 使用如下: class ...

随机推荐

  1. 设置属性节点(setAttribute())

    setAttribute():方法将为给定元素节点添加一个新的属性值或是改变它的现有属性值: element.setAttribute(attriibuteName,attributeValue); ...

  2. ElasticSearch如何一次查询出全部数据—基于Scroll

    Elasticsearch 查询结果默认只显示10条,可以通过设置from及size来达到分页的效果(详见附3),但是 from + size <= 10,000,因为index.max_res ...

  3. Win10无法安装.NET Framework3.5的解决办法

    诸位网友如果工作中使用WIN10遇到如图的这种问题,现将解决办法整理如下: 一.第一步就是修复系统:按“Windows+X”点击“Windows PowerShell(管理员)&命令提示符(管 ...

  4. python迭代器生成器-迭代器和list区别

    迭代 生成 for循环遍历的原理 for循环遍历的原理就是迭代,in后面必须是可迭代对象 为什么要有迭代器 对于序列类型:字符串.列表.元组,我们可以使用索引的方式迭代取出其包含的元素.但对于字典.集 ...

  5. java 算法之 两个字符串中最大相同的子串

    public class String_intern { public static void main(String[] args) { String old="aaaaabc1" ...

  6. 爬取豆瓣top250音乐 时长 出版商 存入Mongo数据库

    import requestsfrom lxml import etreeimport reimport pymongoimport time client = pymongo.MongoClient ...

  7. $("#loginname").tips和jQuery中 的ajax

    jquery tips 提示插件 jquery.tips.js v0.1beta: 使用方法 $("#loginname").tips({ //#loginname为jquery的 ...

  8. IDEA IntelliJ/ DataGrip 修改自动补全快捷键

    系统默认的是Tab键,个人喜欢用空格键作为自动补全键,设置方法如下 Setting-->Keymap-->Editor Actions:Choose Lookup Item Replace ...

  9. 脚本shell每小时递增运行task

    下面 hello 是开始时间, world 是结束时间 #!/bin/bash START=$(date +%s); hello="20160911 00" world=" ...

  10. luogu P1417 烹调方案 |dp

    题目背景 由于你的帮助,火星只遭受了最小的损失.但gw懒得重建家园了,就造了一艘飞船飞向遥远的earth星.不过飞船飞到一半,gw发现了一个很严重的问题:肚子饿了~ gw还是会做饭的,于是拿出了储藏的 ...