一、property属性
property属性可以用来给属性添加约束,比如温度属性,我们不允许低于-273度;成绩属性,我们不允许0分以下等等。而且使用property属性,将来修改约束条件的时候也很方便,可以在代码的调用方式不变的情况下改变结果。
python中使用property属性有两种方法。使用@property装饰器和使用property()函数。这里我们着重学习@property属性
二、@property属性
@property装饰器就是负责把一个方法变成属性调用的。如下实例就可以通过s.score来获得成绩,并且对score赋值之前做出了数据检查。
class Student(object):
def __init__(self, score=0):
self._score = score
@property
def score(self):
print("getting score")
return self._score
@score.setter
def score(self, value):
print("setting score")
if not isinstance(value, int):
raise ValueError(&#