1.1 使用@property
输入成绩score时,需对这个参数进行检查。
>>> class Student(object):
... def get_score(self):
... return self.__score
... def set_score(self, value):
... if not isinstance(value, int):
... raise ValueError(‘score must beinteger‘)
... if value < 0 or value > 100:
... raise ValueError(‘score mustbetween 0 and 100.‘)
... self.__score = value
...
>>> s = Student()
>>> s.set_score(60)
>>> s.get_score()
60
>>> s.set_score(999)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in set_score
ValueError: score must between 0 and 100.
有没有既能检查参数,又可以用类似属性这样简单的方式来访问和修改类的变量呢?
Python内置的@property装饰器就是负责把一个方法变成属性。
>>> class Student(object):
... @property
... def score(self): --score可以理解为属性
... return self.__score --返回属性
... @score.setter
... def score(self, value): --score可以理解为属性
... if not isinstance(value, int):
... raise ValueError(‘Score must be aninteger.‘)
... if value < 0 or value > 100:
... raise ValueError(‘Score mustbetween 0 and 100.‘)
... self.__score = value --修改属性
...
>>> s = Student()
>>> s.score = 60 --修改属性,这里不再是调用方法,score属性可读可写
>>> s.score
60
>>> s.score = -1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 10, in score
ValueError: Score must between 0 and 100.
定义只读属性—只定义getter方法,不定义setter就是只读
>>> class Student(object):
... @property
... def birth(self):
... return self._birth
... @birth.setter
... def birth(self, value):
... self._birth = value --birth可读可写
... @property
... def age(self):
... return 2016 - self._birth --age只读
...
>>> s = Student()
>>> s.birth = 1992
>>> s.birth
1992
>>> s.age
24