定义一个抽象类Shape,包含计算面积和打印方法,并从Shape类派生两个新的类长方形和直角三角形,要求在新类中重写计算面积的方法
时间: 2024-03-05 15:50:15 浏览: 68
以下是Python代码实现:
```python
# 定义抽象类Shape
from abc import ABC, abstractmethod
class Shape(ABC):
# 计算面积
@abstractmethod
def calculate_area(self):
pass
# 打印形状
def print_shape(self):
print("This is a shape.")
# 长方形类
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
# 重写计算面积的方法
def calculate_area(self):
return self.length * self.width
# 重写打印形状的方法
def print_shape(self):
print("This is a rectangle.")
# 直角三角形类
class RightTriangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
# 重写计算面积的方法
def calculate_area(self):
return 0.5 * self.base * self.height
# 重写打印形状的方法
def print_shape(self):
print("This is a right triangle.")
```
在上述代码中,我们定义了一个抽象类Shape,其中包含了计算面积和打印形状的方法。然后分别从Shape类派生了两个新的类Rectangle和RightTriangle,并在新类中重写了计算面积和打印形状的方法。这样,我们就可以根据不同的需求创建不同的形状对象,并调用相应的方法进行计算和打印。
阅读全文
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20250102104920.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)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)