定义形状类Shape,包含方法CalculatedArea() 2.定义形状类的子类:矩形Rectangle、平行四边形Parallelogram、圆形Circle和三角形triangle 3.定义运算类Operation,可以计算所有形状的面积
时间: 2023-06-11 17:09:31 浏览: 98
代码如下:
```python
class Shape:
def CalculatedArea(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def CalculatedArea(self):
return self.width * self.height
class Parallelogram(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def CalculatedArea(self):
return self.base * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def CalculatedArea(self):
return 3.14 * (self.radius ** 2)
class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def CalculatedArea(self):
return 0.5 * self.base * self.height
class Operation:
def __init__(self, shape):
self.shape = shape
def CalculateArea(self):
return self.shape.CalculatedArea()
# 示例使用
r = Rectangle(5, 10)
p = Parallelogram(6, 8)
c = Circle(4)
t = Triangle(3, 5)
op1 = Operation(r)
op2 = Operation(p)
op3 = Operation(c)
op4 = Operation(t)
print(op1.CalculateArea()) # 输出50
print(op2.CalculateArea()) # 输出48
print(op3.CalculateArea()) # 输出50.24
print(op4.CalculateArea()) # 输出7.5
```
以上代码定义了一个`Shape`类作为基类,包含了一个`CalculatedArea()`方法,但并未实现具体的计算面积的逻辑。然后,又定义了`Rectangle`、`Parallelogram`、`Circle`和`Triangle`四个子类,并分别实现了自己的`CalculatedArea()`方法。最后,定义了一个`Operation`类,该类的实例可以计算任何形状的面积,其接收一个形状实例作为初始化参数,并在`CalculateArea()`方法中调用其对应的`CalculatedArea()`方法进行计算。示例中定义了四种不同的形状实例,并分别通过`Operation`类的实例进行面积计算。