绑定属性时,如果直接暴露属性,虽然写起来很简单,但是没有办法检查参数,导致结果可以随意改变:
s=Student() s.score=9999
这显然是不合逻辑的。为了限制score的范围,可以通过一个set_score()
设置结果的方法,然后通过一种方法get_score()
为了获得成绩,这样,在set_score()
在方法中,可以检查参数:
classStudent(object): defget_score(self): returnself._score defset_score(self,value): ifnotisinstance(value,int): raiseValueError('scoremustbeaninteger!') ifvalue<0orvalue>100: raiseValueError('scoremustbetwen0~100!') self._score=value
现在,操作任何Student实例,都不能随意设置score:
>>>s=Student() >>>s.set_score(60)#ok! >>>s.get_score()60 >>>s.set_score(9999) Traceback(mostrecentcalllast): ... ValueError:scoremustbetwen0~100!
但以上调用方法略显复杂,没有直接使用属性那么简单。
您是否可以以类似属性的简单方式检查参数并访问类变量?对于追求完美的Python程序员来说,这是必须的!
还记得装饰(decorator)函数动态可以添加功能吗?装饰器也起作用于类别方法。Python内置@property
装饰负责将一种方法转化为属性调用:
classStudent(object): @property defscore(self): returnself._score @score.setter defscore(self,value): ifnotisinstance(value,int): raiseValueError('scoremustbeaninteger!') ifvalue<0orvalue>100: raiseValueError('scoremustbetwen0~100!') self._score=value
@property
实现比较复杂,先考察怎么用。只需添加一个getter方法来将其转化为属性@property
可以,此时,@property
又创造了另一个装饰品@score.setter
,负责将setter方法转化为属性赋值,因此,我们有一个可控的属性操作:
>>>s=Student() >>>s.score=60#OK,实际转化为s.set_score(60) >>>s.score#OK,实际转化为s.get_score()60 >>>s.score=999Traceback(mostrecentcalllast): ... ValueError:scoremustbetwen0~100!
注意这个神奇的东西@property
,当我们操作实例属性时,我们知道这个属性很可能不是直接暴露的,而是通过getter和setter来实现的。
也可以定义只读属性,只定义getter方法,不定义setter方法是只读属性:
classStudent(object): @property defbirth(self): returnself._birth @birth.setter defbirth(self,value): self._birth=value @property defage(self): return2015年-self._birth
上面的birth
是可读写属性,而age
就是一个只读属性,因为age
可以根据birth
计算当前时间。
@property
广泛应用于类别定义,允许调用器编写短代码,并确保必要的参数检查,从而减少程序运行中出错的可能性。
有关python的更多文章,请关注python自学网。