定义一个shape类,利用它作为基类派生出Rectangle、Circle等具体形状类,已知具体形状类均具有两个方法GetArea和GetColor,分别用来得到形状的面积和颜色。最后编,写一个测试程序对产生的类的功能进行验证。
时间: 2023-11-13 16:40:29 浏览: 26
可以为您编写一个基本的Python代码来实现您的需求:
```python
class Shape:
def __init__(self, color):
self.color = color
def get_area(self):
pass
def get_color(self):
return self.color
class Rectangle(Shape):
def __init__(self, color, width, height):
super().__init__(color)
self.width = width
self.height = height
def get_area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, color, radius):
super().__init__(color)
self.radius = radius
def get_area(self):
return 3.14 * (self.radius ** 2)
# 测试程序
rectangle = Rectangle("red", 4, 6)
print("Rectangle area:", rectangle.get_area())
print("Rectangle color:", rectangle.get_color())
circle = Circle("blue", 3)
print("Circle area:", circle.get_area())
print("Circle color:", circle.get_color())
```
这段代码定义了一个`Shape`类作为基类,并派生出`Rectangle`和`Circle`两个具体形状类。每个具体形状类都重写了基类的`get_area`方法,并添加了自己特有的属性和方法。在测试程序中,我们创建了一个`Rectangle`对象和一个`Circle`对象,并调用相应的方法来验证它们的功能。
相关推荐
![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)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)