定义一个shape类,利用它作为基类派生出Rectangle、Circle等具体形状类,已知具体形状类均具有两个方法GetArea和GetColor,分别用来得到形状的面积和颜色。最后编,写一个测试程序对产生的类的功能进行验证。
时间: 2023-11-13 08:40:29 浏览: 143
以下是对你的要求编写的代码:
```python
class Shape:
def __init__(self, color):
self.color = color
def GetArea(self):
pass
def GetColor(self):
return self.color
class Rectangle(Shape):
def __init__(self, color, width, height):
super().__init__(color)
self.width = width
self.height = height
def GetArea(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, color, radius):
super().__init__(color)
self.radius = radius
def GetArea(self):
return 3.14159 * self.radius ** 2
# 测试程序
rect = Rectangle("red", 5, 8)
print("Rectangle Area:", rect.GetArea())
print("Rectangle Color:", rect.GetColor())
circle = Circle("blue", 3)
print("Circle Area:", circle.GetArea())
print("Circle Color:", circle.GetColor())
```
运行上述代码,输出结果为:
```
Rectangle Area: 40
Rectangle Color: red
Circle Area: 28.27431
Circle Color: blue
```
这个程序定义了一个Shape类作为基类,并派生出Rectangle和Circle两个具体形状类。每个具体形状类都继承了基类的GetColor方法,并实现了自己的GetArea方法。测试程序创建了一个Rectangle对象和一个Circle对象,并调用它们的GetArea和GetColor方法进行验证。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)