常规的get和set方法写法如下,虽然能对写入数据进行校验和控制,但同时暴露了get和set方法,不够简洁:
class Student(object): count = 0 def __init__(self, name, score): self.__name = name self.__score = score Student.count += 1 def get_name(self): return self.__name def get_score(self): return self.__score def set_score(self, score): if isinstance(score, int) and 0 <= score <= 100: self.__score = score else: raise ValueError("Score必需是0~100的整数。") s1 = Student("潘承",60) print(s1.get_name()) s1.set_score(89) print(s1.get_score())
于是追求简洁和完美的开发同学不满意了,他们希望在能保留校验的情况下,能像访问常规属性一样去进行get和set的操作。
比如上面的 get_score 和 set_score,他们希望写成 xxx = obj.score 和 obj.score = xxx。
python提供了property装饰器来满足这些同学的要求,代码如下:
class Student(object): count = 0 def __init__(self, name, score): self.__name = name self.__score = score Student.count += 1 @property def name(self): return self.__name @property def score(self): return self.__score @score.setter #注意setter装饰器的写法 def score(self, score): if isinstance(score, int) and 0 <= score <= 100: self.__score = score else: raise ValueError("Score必需是0~100的整数。") s1 = Student("潘承",60) print(s1.name) s1.score = 90 print(s1.score) # 只需要用 obj.score就可以进行读写操作,同时保留校验