class Screen(object):
@property
def width(self):
return self._width
@width.setter
def width(self,value):
self._width = value
@property
def height(self):
return height._width
@height.setter
def height(self,value):
self._height = value
@property
def resolution(self):
return self._width * self._height
Python内置的@property装饰器就是负责把一个方法变成属性调用的。
class Student(object):
def get_score(self):
return self._score
def set_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
相对于这种方法,@property方法更简便,不易出错