property
作用
把方法变为属性,只可以用来访问
好处
可以方便的访问属性,同时加上了函数的各种检查
例子
class Student(object):
@property
def score(self):
return self._score
@score.setter
def score(self, value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
self._score = value
s = Student()
s.score = 60 # OK,实际转化为s.set_score(60)
print(s.score) # OK,实际转化为s.get_score()
s.score = 9999
输出
60
Traceback (most recent call last):
File "/Users/Reno_Lei/PycharmProjects/filteralchemy/cc.py", line 18, in <module>
s.score = 9999
File "/Users/Reno_Lei/PycharmProjects/filteralchemy/cc.py", line 12, in score
raise ValueError('score must between 0 ~ 100!')
ValueError: score must between 0 ~ 100!
Setter 装饰器
作用
把方法变为属性,可以用来赋值
好处
封装变量的同时,给了外部良好的设置接口,非常简单易用
class Student(object):
@property
def score(self):
return self._score
@score.setter
def score(self, value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
self._score = value
s = Student()
s.score = 60 # OK,实际转化为s.set_score(60)
print(s.score) # OK,实际转化为s.get_score()
s.score = 9999
s.score = 60 就是使用了setter装饰器