Python @property使用方法解析
2019-09-17 14:31
1326 查看
1. 作用
将类方法转换为类属性,可以用 . 直接获取属性值或者对属性进行赋值
2.实现方式
使用property类来实现,也可以使用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 student = Student()student.score = 65print(student.score)65
score()方法上增加@property装饰器,等同于score= property(fget=score),将score赋值为property的实例。
所以,被装饰后的score,已经不是这个实例方法score了,而是property的实例score。
以上就是本文的全部内容,希望对大家的学习有所帮助
您可能感兴趣的文章:
相关文章推荐
- 详解Python使用simplejson模块解析JSON的方法
- 详解Python使用simplejson模块解析JSON的方法
- python解析html开发库pyquery使用方法
- 使用Python解析JSON数据的基本方法
- Python使用@property方法改变方法为参数
- python 访问器@property的使用方法
- 使用Python解析JSON数据的基本方法
- python爬虫selenium和phantomJs使用方法解析
- python数据持久存储 pickle模块的基本使用方法解析
- python 各种解析xml包使用方法总结 - 转
- python 解析xml包使用方法总结
- ##########(python 解析参数方法 可用) Python optionParser模块的使用方法 #######
- python 访问器@property的使用方法
- 使用PYTHON解析Wireshark的PCAP文件方法
- 使用Python解析JSON数据的基本方法
- python解析模块(ConfigParser)使用方法
- python 各种解析xml包使用方法总结
- python函数修饰符@的使用方法解析
- 全面解析Python的While循环语句的使用方法
- 全面解析Python的While循环语句的使用方法