设计一个基类Shape。该类包含3个属性:图形名称(name),图形面积(area),图形周长(perimeter)。该类包含3个成员函数:calArea()—计算并返回该图形的面积;calPerimeter()—计算并返回该图形的周长;display()—打印输出图形名称,面积,周长。设计3个派生类:Rectangle,Triangle,Circle,请为派生类定义合适的数据成员用于表达其结构,派生类应重载实现基类中的全部成员函数。
时间: 2023-12-31 13:04:08 浏览: 135
好的,以下是基类Shape的实现代码:
```python
class Shape:
def __init__(self, name):
self.name = name
self.area = 0
self.perimeter = 0
def calArea(self):
pass
def calPerimeter(self):
pass
def display(self):
print("图形名称:", self.name)
print("图形面积:", self.area)
print("图形周长:", self.perimeter)
```
接下来是Rectangle类的实现代码:
```python
class Rectangle(Shape):
def __init__(self, name, width, height):
super().__init__(name)
self.width = width
self.height = height
def calArea(self):
self.area = self.width * self.height
return self.area
def calPerimeter(self):
self.perimeter = 2 * (self.width + self.height)
return self.perimeter
```
接下来是Triangle类的实现代码:
```python
class Triangle(Shape):
def __init__(self, name, a, b, c):
super().__init__(name)
self.a = a
self.b = b
self.c = c
def calArea(self):
p = (self.a + self.b + self.c) / 2
self.area = (p * (p - self.a) * (p - self.b) * (p - self.c)) ** 0.5
return self.area
def calPerimeter(self):
self.perimeter = self.a + self.b + self.c
return self.perimeter
```
接下来是Circle类的实现代码:
```python
class Circle(Shape):
def __init__(self, name, radius):
super().__init__(name)
self.radius = radius
def calArea(self):
self.area = 3.14 * self.radius ** 2
return self.area
def calPerimeter(self):
self.perimeter = 2 * 3.14 * self.radius
return self.perimeter
```
以上就是Shape及其三个派生类的实现代码,可以通过以下方式来使用:
```python
rect = Rectangle("长方形", 5, 10)
rect.calArea()
rect.calPerimeter()
rect.display()
tri = Triangle("三角形", 3, 4, 5)
tri.calArea()
tri.calPerimeter()
tri.display()
cir = Circle("圆形", 5)
cir.calArea()
cir.calPerimeter()
cir.display()
```
阅读全文