用Python定义一个可以计算圆、三角形、长方形、面积和周长的类
时间: 2023-07-10 09:43:03 浏览: 103
好的,以下是一个可以计算圆、三角形、长方形面积和周长的类,代码如下:
```python
import math
class Shape:
def __init__(self):
self.area = 0
self.perimeter = 0
def calculate_area(self):
pass
def calculate_perimeter(self):
pass
class Circle(Shape):
def __init__(self, radius):
super().__init__()
self.radius = radius
def calculate_area(self):
self.area = math.pi * self.radius ** 2
def calculate_perimeter(self):
self.perimeter = 2 * math.pi * self.radius
class Triangle(Shape):
def __init__(self, a, b, c):
super().__init__()
self.a = a
self.b = b
self.c = c
def calculate_area(self):
s = (self.a + self.b + self.c) / 2
self.area = math.sqrt(s * (s - self.a) * (s - self.b) * (s - self.c))
def calculate_perimeter(self):
self.perimeter = self.a + self.b + self.c
class Rectangle(Shape):
def __init__(self, width, height):
super().__init__()
self.width = width
self.height = height
def calculate_area(self):
self.area = self.width * self.height
def calculate_perimeter(self):
self.perimeter = 2 * (self.width + self.height)
```
使用方法:
```python
# 计算圆的面积和周长
circle = Circle(5)
circle.calculate_area()
circle.calculate_perimeter()
print("Circle area:", circle.area)
print("Circle perimeter:", circle.perimeter)
# 计算三角形的面积和周长
triangle = Triangle(3, 4, 5)
triangle.calculate_area()
triangle.calculate_perimeter()
print("Triangle area:", triangle.area)
print("Triangle perimeter:", triangle.perimeter)
# 计算长方形的面积和周长
rectangle = Rectangle(2, 4)
rectangle.calculate_area()
rectangle.calculate_perimeter()
print("Rectangle area:", rectangle.area)
print("Rectangle perimeter:", rectangle.perimeter)
```
输出结果:
```
Circle area: 78.53981633974483
Circle perimeter: 31.41592653589793
Triangle area: 6.0
Triangle perimeter: 12
Rectangle area: 8
Rectangle perimeter: 12
```
阅读全文