Python 面向对象高级编程――使用@property
2016-07-13 22:56
836 查看
1.1 使用@property
输入成绩score时,需对这个参数进行检查。>>> class Student(object):
... def get_score(self):
... return self.__score
... def set_score(self, value):
... if not isinstance(value, int):
... raise ValueError('score must beinteger')
... if value < 0 or value > 100:
... raise ValueError('score mustbetween 0 and 100.')
... self.__score = value
...
>>> s = Student()
>>> s.set_score(60)
>>> s.get_score()
60
>>> s.set_score(999)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in set_score
ValueError: score must between 0 and 100.
有没有既能检查参数,又可以用类似属性这样简单的方式来访问和修改类的变量呢?
Python内置的@property装饰器就是负责把一个方法变成属性。
>>> class Student(object):
... @property
... def score(self): --score可以理解为属性
... return self.__score --返回属性
... @score.setter
... def score(self, value): --score可以理解为属性
... if not isinstance(value, int):
... raise ValueError('Score must be aninteger.')
... if value < 0 or value > 100:
... raise ValueError('Score mustbetween 0 and 100.')
... self.__score = value --修改属性
...
>>> s = Student()
>>> s.score = 60 --修改属性,这里不再是调用方法,score属性可读可写
>>> s.score
60
>>> s.score = -1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 10, in score
ValueError: Score must between 0 and 100.
定义只读属性―只定义getter方法,不定义setter就是只读
>>> class Student(object):
... @property
... def birth(self):
... return self._birth
... @birth.setter
... def birth(self, value):
... self._birth = value --birth可读可写
... @property
... def age(self):
... return 2016 - self._birth --age只读
...
>>> s = Student()
>>> s.birth = 1992
>>> s.birth
1992
>>> s.age
24
本文出自 “90SirDB” 博客,请务必保留此出处http://90sirdb.blog.51cto.com/8713279/1826208
相关文章推荐
- Python 面向对象高级编程――使用__slots__
- Python语言及其应用 第2章
- Python 面向对象编程――获取对象信息
- Python 面向对象编程――继承和多态
- Python 面向对象编程——访问控制
- Python 面向对象编程——类和实例
- Python + Android + Uiautomator自动化测试
- python学习例程1-helloword
- 不用加减乘除做加法中Python存在的bug
- 使用uiautomator的python封装进行android的UI测试
- python之socket编程(二)
- python实现模拟按键,自动翻页看u17漫画
- python3解释器
- Python模拟浏览器登陆网站
- Opencv 和Python的连接及配置环境变量
- Python模拟用户自动登陆网易126邮箱
- Python开发工具
- 使用Python控制IE访问网站
- Python扫描指定目录下(包括子目录)的文件
- 一个python学习的好地方