Others
描述符
"""
某日,假设你需要一个类,来记录数学考试的分数。但是稍后你就发现了问题:分数为负值是没有意义的。
# class Score:
# def __init__(self, math):
# if math < 0:
# raise ValueError('math score must >= 0')
# self.math = math
但这样也没解决问题,因为分数虽然在初始化时不能为负,但后续修改时还是可以输入非法值:幸运的是,有内置装饰器 @property 可以解决此问题。
"""
class Score:
def __init__(self, math):
self.math = math
@property
def math(self):
# self.math 取值
return self._math
@math.setter
def math(self, value):
# self.math 赋值
if value < 0:
raise ValueError('math score must >= 0')
self._math = value
score = Score(90)
score.math =34
score._math # 34Cache
The normal built-in cache
Validator
Last updated
Was this helpful?