classStudent(object):defget_score(self):return self._scoredefset_score(self,value):ifnotisinstance(value, int):raiseValueError('score must be an integer!')if value <0or value >100:raiseValueError('score must between 0 ~ 100!') self._score = value
现在,对任意的Student实例进行操作,就不能随心所欲地设置score了:
>>> s =Student()>>> s.set_score(60)# ok!>>> s.get_score()60>>> s.set_score(9999)Traceback (most recent call last): ...ValueError: score must between 0~100!
classStudent(object):@propertydefscore(self):return self._score@score.setterdefscore(self,value):ifnotisinstance(value, int):raiseValueError('score must be an integer!')if value <0or value >100:raiseValueError('score must between 0 ~ 100!') self._score = value