- Python内置的@property装饰器,把一个方法,变成可以像属性那样,做取值用
- @score.setter,把一个方法,变成可以像属性那样,作赋值用
- @property和score.setter()同时,表示可读可写
- 只有@property,表示只读
- 下面的score()本身是一个方法,本来的用法是s.score()
- 经过@property,可以像属性那样用s.score,不加括号
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)
s.score # OK,实际转化为s.get_score()
练习:请利用@property给一个Screen对象加上width和height属性,以及一个只读属性resolution
class Screen(object):
@property
def width(self):
return self._width
@width.setter
def width(self,value):
self._width=value
@property
def height(self):
return self._height
@height.setter
def height(self,value):
self._height=value
@property
def resolution(self):
self._resolution=self._width*self._height
return self._resolution
s = Screen()
s.width = 1024
s.height = 768
print('resolution =', s.resolution)
if s.resolution == 786432:
print('测试通过!')
else:
print('测试失败!')
网友评论