This is obviously illogical. To limit the scope of the score, you can set the score by one method, and set_score()
then get the score by one, get_score()
so that in the set_score()
method, you can check the parameters:
class studentdef get_scorereturn self._score def set_scoreif not Isinstance (value, int): raise valueerror ( ' score must is an integer! ') if value < 0 or value > 100: span class= "keyword" >raise valueerror ( ' score must between 0 ~ 100! ') Self._score = value span>
Remember the adorner (decorator) can add functionality to a function dynamically? For class methods, adorners work as well. Python's built-in @property
adorner is responsible for turning a method into a property call:
class student (object): @ Property def scorereturn self._score @score. Setter def score (self, value): if not isinstance (value, int): raise valueerror (if value < 0 or value > : raise valueerror ( ' score must between 0 ~ 100! ') Self._score = value
@property
Implementation is more complex, we first examine how to use. To turn a getter method into a property, just add it, and @property
at this point, it @property
creates another adorner @score.setter
, which is responsible for turning a setter method into a property assignment, so we have a controllable property operation:
>>> s = Student()>>> s.score = 60 # OK,实际转化为s.set_score(60)>>> s.score # OK,实际转化为s.get_score()60>>> s.score = 9999Traceback (most recent call last): ...ValueError: score must between 0 ~ 100!
Notice that this magical @property
, when we operate on instance properties, we know that this property is probably not directly exposed, but is implemented through getter and setter methods.
Python practical Note (23) object-oriented advanced programming-using @property