码迷,mamicode.com
首页 > 编程语言 > 详细

python @property装饰器

时间:2018-02-24 10:50:09      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:elf   需要   读写   ror   pytho   integer   setter   obj   property   

@property装饰器

@property装饰器就是负责把一个方法变成属性调用
把一个getter方法变成属性,只需要加上@property就可以了,
此时,@property本身又创建了另一个装饰器@score.setter,负责把一个setter方法变成属性赋值
class Student(object):

@property
def score(self):
return self._score

@score.setter
def score(self, value):
if not isinstance(value, int):
raise ValueError(‘score must be an integer!‘)
。。。
还可以定义只读属性,只定义getter方法,不定义setter方法就是一个只读属性
class Student(object):

@property
def birth(self):
return self._birth

@birth.setter
def birth(self, value):
self._birth = value

@property
def age(self):
return 2015 - self._birth

birth是可读写属性,而age就是一个只读属性

python @property装饰器

标签:elf   需要   读写   ror   pytho   integer   setter   obj   property   

原文地址:https://www.cnblogs.com/wander-clouds/p/8458168.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!