设计一个基类Shape。该类包含3个属性:图形名称(name)、图形面积(area)和图形周(perimeter)。该类包含3个成员函数:calArea()一计算并返回该图形的面积;calp. erimeter()一计算并返回该图形的周长;display()一打印输出图形名称、面积、周长。设计3 个派生类:Rectangle、Triangle、Circle,请为派生类定义合适的数据成员用于表达其结构,派生类应重载实现基类中的全部成员函数。
时间: 2024-02-01 13:13:12 浏览: 92
矩形类及派生类,算面积、体积
以下是基类Shape和派生类Rectangle、Triangle、Circle的实现:
```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("Shape Name:", self.name)
print("Area:", self.area)
print("Perimeter:", self.perimeter)
class Rectangle(Shape):
def __init__(self, name, length, width):
super().__init__(name)
self.length = length
self.width = width
def calArea(self):
self.area = self.length * self.width
def calPerimeter(self):
self.perimeter = 2 * (self.length + self.width)
class Triangle(Shape):
def __init__(self, name, side1, side2, side3):
super().__init__(name)
self.side1 = side1
self.side2 = side2
self.side3 = side3
def calArea(self):
s = (self.side1 + self.side2 + self.side3) / 2
self.area = (s * (s - self.side1) * (s - self.side2) * (s - self.side3)) ** 0.5
def calPerimeter(self):
self.perimeter = self.side1 + self.side2 + self.side3
class Circle(Shape):
def __init__(self, name, radius):
super().__init__(name)
self.radius = radius
def calArea(self):
self.area = 3.14 * self.radius ** 2
def calPerimeter(self):
self.perimeter = 2 * 3.14 * self.radius
```
在上面的代码中,基类Shape包含了图形的名称、面积和周长,以及计算这些值的方法。派生类Rectangle、Triangle、Circle继承了基类Shape,并重载了基类中的全部成员函数,以便能够计算出它们各自的面积和周长。在每个派生类的构造函数中,我们还定义了适当的数据成员来表示每种特定的图形的结构。最后,我们可以创建这些图形的对象,并使用它们的方法来计算面积和周长,然后将它们打印出来。以下是一个示例:
```python
rect = Rectangle("Rectangle", 5, 10)
rect.calArea()
rect.calPerimeter()
rect.display()
tri = Triangle("Triangle", 3, 4, 5)
tri.calArea()
tri.calPerimeter()
tri.display()
circ = Circle("Circle", 7)
circ.calArea()
circ.calPerimeter()
circ.display()
```
输出如下:
```
Shape Name: Rectangle
Area: 50
Perimeter: 30
Shape Name: Triangle
Area: 6.0
Perimeter: 12
Shape Name: Circle
Area: 153.86
Perimeter: 43.96
```
阅读全文