python中@property的使用
2015-07-10 19:49
861 查看
python中@property的使用
@property的作用是把一个getter方法变成属性,@xxx.setter把setter方法变成属性赋值。#coding:utf-8 class Screen(object): @property def width(self): return self._width @width.setter def width(self,value): if not isinstance(value,int): raise ValueError('width must be a integer') elif value<0: raise ValueError('width must greater than zero') else: self._width=value @property def height(self): return self._height @height.setter def height(self,value): if not isinstance(value,int): raise ValueError('height must be a integer') elif value<0: raise ValueError('height must greater than zero') else: self._height=value @property def revolution(self): return self._width*self._height #测试 s=Screen() s._width=30 s._height=40 print(s.width) print(s.height) print(s.revolution)
这是看廖雪峰老师的教程上面的一个练习题,做了下,发现了下面问题。
在类中的变量中的下划线不能少,否则,会报错,原因在于:如果不加下划线出现self.width时就会继续调用此类的getter方法出现死循环。这个是我们需要注意的。
相关文章推荐
- Install Deepdream(Caffe-python) on Mac OS X
- 邀请码生成析
- python并行处理任务时 该用多进程?还是该用多线程?
- [Python] Python 之 __new__() 方法与实例化
- 说说Python程序的执行过程
- python logging
- Python中and和or
- python学习笔记——Tkinter GUI编程——简介
- 对python中的字典进行排序
- Python实现分割文件及合并文件的方法
- python 编码问题——字符编码
- python基础课程_学习笔记26:编程的乐趣
- Python学习笔记5
- Python写入数据到MP3文件中的方法
- 模拟登陆之填入cookie【python】
- 【python】多进程多线程
- Python将阿拉伯数字转换为罗马数字的方法
- Python自动登录126邮箱的方法
- Python获取邮件地址的方法
- python实现中文分词FMM算法实例