[python]代码库
# -*- coding: utf-8 -*-
'''请利用@property给一个Screen对象加上width和height属性,
以及一个只读属性resolution'''
class Screen(object):
__slots__ = ('_width','_height')
@property
def width(self):
return self._width
@property
def height(self):
return self._height
@property
def resolution(self):
if not self._width:
raise ValueError('width is wrong!')
if not self._height:
raise ValueError('height is wrong!')
else:
return self._width*self._height
@width.setter
def width(self,value):
self._width = value
@height.setter
def height(self,value):
self._height = value
wh = Screen()
wh.width=10
wh.height=20
#wh.kuan=20 'Screen' object has no attribute 'kuan'
print('wh.width(10)',wh.width)
print('wh.height(20)',wh.height)
print('wh.resolution',wh.resolution)
s = Screen()
s.width = 1024
s.height = 768
print('resolution =', s.resolution)
if s.resolution == 786432:
print('测试通过!')
else:
print('测试失败!')