(1) 实现一个名为“Rectangle”的表示矩形的类,该类包含两个公有的实例属性width和height,分别表示矩形的宽和高,同时还有一个名为aera的公有方法,该方法返回长为3.1,宽为4.5的矩形的面积。 (2) 修改上一步中的Rectangle类,将实例属性width和height改为可读写的property,并且在写操作时检查是否为正值,将area方法改为一个只读的property该方法返回长为3.1,宽为4.5的矩形的面积。 。 (3) 继承上一步中的Rectangle类来实现一个名为Square的正方形类,使得可以用Square(边长)的方式实例化该类,并重写父类中width和height的写方法,实现长和高的同时修改,该方法返回边长为4的长方形的面积。 。
时间: 2023-06-04 10:04:33 浏览: 192
答:(1) 实现代码:
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return 3.1 * 4.5
r = Rectangle(3.1, 4.5)
print(r.area())
(2) 修改后的代码:
class Rectangle:
def __init__(self, width, height):
self._width = width
self._height = height
@property
def width(self):
return self._width
@width.setter
def width(self, value):
if value > 0:
self._width = value
else:
raise ValueError("Width value must be positive")
@property
def height(self):
return self._height
@height.setter
def height(self, value):
if value > 0:
self._height = value
else:
raise ValueError("Height value must be positive")
@property
def area(self):
return self._width * self._height
r = Rectangle(3.1, 4.5)
print(r.area)
r.width = 5.0
print(r.width)
r.height = 6.0
print(r.area)
(3) 继承并重写的代码:
class Square(Rectangle):
def __init__(self, side_length):
super().__init__(side_length, side_length)
@Rectangle.width.setter
def width(self, value):
if value > 0:
self._width = value
self._height = value
else:
raise ValueError("Width value must be positive")
s = Square(4)
print(s.area)
s.width = 5
print(s.area)
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)