@property:(把方法变成属性调用)
Python内置的@property装饰器就是负责把一个方法变成属性调用的
Python允许我们在程序中手动设置异常,使用 raise 语句即可
把一个getter方法变成属性,只需要加上@property就可以了,此时,@property本身又创建了另一个装饰器@score.setter,负责把一个setter方法变成属性赋值,于是,我们就拥有一个可控的属性操作
# 例1:学生分数设置和获取
class Student(object):
@property
def score(self):
return self._score
@score.setter
def score(self, value):
if not isinstance(value, int):
raise TypeError('score must be an integer')
if value > 100 or value < 0:
raise ValueError('score must be between 0 and 100')
self._score = value
s1 = Student()
s1.score = 100 # 实际就是set_score
print(s1.score) # 实际就是get_score
还可以定义只读属性,只定义getter方法,不定义setter方法就是一个只读属性
# 例2:学生生日的设置和获取
class Student(object):
@property
def birthday(self):
return self._birthday
@birthday.setter
def birthday(self, value):
self._birthday = value
def age(self):
return 2020 - self._birthday
s1 = Student()
s1.birthday = 1998
print(s1.birthday)
print(s1.age())
请利用@property给一个Screen对象加上width和height属性,以及一个只读属性resolution
# 例3:计算长方形的面积
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):
return self._width * self._height
s = Screen()
s.width = 1024
s.height = 768
print('resolution =', s.resolution)
if s.resolution == 786432:
print('测试通过!')
else:
print('测试失败!')