用抽象类的方法定义基本几何图形的基类(Shape),然后在 Shape类中定义抽象方法面积的方法getArea() 及边长getLength()的抽象方法 用定义接口类的方法定义基本几何图形的基类(ShapeI),然后在 ShapeI类中定义抽象方法面积的方法getArea() 及边长getLength()的抽象方法 然后定义Shape的派生类Circle(圆),Square(正方形)和Triangle(三角形)。要求通过方法覆盖来计算各种图形的面积和周长。
时间: 2024-02-28 12:57:18 浏览: 22
好的,我理解你的问题了。下面是对应的代码实现:
使用抽象类的方法定义基本几何图形的基类(Shape):
```python
from abc import ABC, abstractmethod # 引入抽象类和抽象方法
class Shape(ABC): # 定义抽象类 Shape
@abstractmethod # 定义抽象方法 getArea()
def getArea(self):
pass
@abstractmethod # 定义抽象方法 getLength()
def getLength(self):
pass
```
使用接口类的方法定义基本几何图形的基类(ShapeI):
```python
from abc import ABC, abstractmethod # 引入抽象类和抽象方法
class ShapeI(ABC): # 定义接口类 ShapeI
@abstractmethod # 定义抽象方法 getArea()
def getArea(self):
pass
@abstractmethod # 定义抽象方法 getLength()
def getLength(self):
pass
```
定义 Shape 的派生类 Circle(圆):
```python
import math
from Shape import Shape # 引入抽象类 Shape
class Circle(Shape): # 定义 Circle 类继承 Shape 抽象类
def __init__(self, radius):
self.radius = radius # 初始化半径
def getArea(self): # 重写抽象方法 getArea()
return math.pi * self.radius ** 2 # 计算圆的面积
def getLength(self): # 重写抽象方法 getLength()
return 2 * math.pi * self.radius # 计算圆的周长
```
定义 Shape 的派生类 Square(正方形):
```python
from Shape import Shape # 引入抽象类 Shape
class Square(Shape): # 定义 Square 类继承 Shape 抽象类
def __init__(self, length):
self.length = length # 初始化边长
def getArea(self): # 重写抽象方法 getArea()
return self.length ** 2 # 计算正方形的面积
def getLength(self): # 重写抽象方法 getLength()
return 4 * self.length # 计算正方形的周长
```
定义 Shape 的派生类 Triangle(三角形):
```python
from Shape import Shape # 引入抽象类 Shape
class Triangle(Shape): # 定义 Triangle 类继承 Shape 抽象类
def __init__(self, a, b, c):
self.a = a # 初始化三角形三边长
self.b = b
self.c = c
def getArea(self): # 重写抽象方法 getArea()
p = (self.a + self.b + self.c) / 2 # 计算半周长
return (p * (p - self.a) * (p - self.b) * (p - self.c)) ** 0.5 # 计算三角形的面积
def getLength(self): # 重写抽象方法 getLength()
return self.a + self.b + self.c # 计算三角形的周长
```
通过这些代码,我们可以计算出 Circle、Square 和 Triangle 的面积和周长。