用python编写代码,定义一个形状基类,有2个属性:面积和周长,以及两个无返回值的方法:area()和perimeter(),分别计算形状的面积和周长,从基类派生出三个子类:三角形、矩形、圆,重载基类的两个方法。
时间: 2023-06-20 13:06:21 浏览: 165
以下是代码实现:
```python
import math
class Shape:
def __init__(self):
self.area_val = 0
self.perimeter_val = 0
def area(self):
pass
def perimeter(self):
pass
class Triangle(Shape):
def __init__(self, a, b, c):
super().__init__()
self.a = a
self.b = b
self.c = c
def area(self):
s = (self.a + self.b + self.c) / 2
self.area_val = math.sqrt(s * (s - self.a) * (s - self.b) * (s - self.c))
return self.area_val
def perimeter(self):
self.perimeter_val = self.a + self.b + self.c
return self.perimeter_val
class Rectangle(Shape):
def __init__(self, width, height):
super().__init__()
self.width = width
self.height = height
def area(self):
self.area_val = self.width * self.height
return self.area_val
def perimeter(self):
self.perimeter_val = 2 * (self.width + self.height)
return self.perimeter_val
class Circle(Shape):
def __init__(self, radius):
super().__init__()
self.radius = radius
def area(self):
self.area_val = math.pi * self.radius ** 2
return self.area_val
def perimeter(self):
self.perimeter_val = 2 * math.pi * self.radius
return self.perimeter_val
```
接下来可以用以下代码进行测试:
```python
t = Triangle(3, 4, 5)
print("Triangle area:", t.area())
print("Triangle perimeter:", t.perimeter())
r = Rectangle(2, 3)
print("Rectangle area:", r.area())
print("Rectangle perimeter:", r.perimeter())
c = Circle(5)
print("Circle area:", c.area())
print("Circle perimeter:", c.perimeter())
```
输出:
```
Triangle area: 6.0
Triangle perimeter: 12
Rectangle area: 6
Rectangle perimeter: 10
Circle area: 78.53981633974483
Circle perimeter: 31.41592653589793
```
阅读全文