在定义一个类的时候,如果我们直接把类中的属性暴露出去,虽然写起来很简单,但是,没办法检查参数,导致可以把成绩随便改,如:
class Student():
score = 10
s = Student()
print(s.score)
s.score = 60
输出:
10
60
这显然不合逻辑。
Python内置的@property装饰器能把一个方法变成属性调用:
class Student(object):
def __init__(self, score):
self._score = score
@property
def score(self):
return self._score
s = Student(50)
print(s.score)
日持score()方法就变成了一个只读属性。这里property装饰器还有一个功能就是能够自动生成一个**@score.setter**装饰器,通过这个装饰器就可以更改score的值了,具体实现如下
class Student(object):
def __init__(self, score):
self._score = score
@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(50)
print(s.score)
s.score = 60
print(s.score)
输出:
50
60