用Python定义一个可以计算圆、三角形、长方形、面积和周长的类
时间: 2023-07-10 11:43:02 浏览: 125
python 输入半径计算圆的周长和面积 示例
5星 · 资源好评率100%
好的,下面是一个可以计算圆、三角形、长方形面积和周长的类的示例代码:
```python
import math
class Shape:
def __init__(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
def perimeter(self):
return 2 * math.pi * self.radius
class Triangle(Shape):
def __init__(self, base, height, side1, side2, side3):
self.base = base
self.height = height
self.side1 = side1
self.side2 = side2
self.side3 = side3
def area(self):
return 0.5 * self.base * self.height
def perimeter(self):
return self.side1 + self.side2 + self.side3
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * (self.length + self.width)
```
在这个示例代码中,我们定义了一个`Shape`基类,然后分别定义了圆形、三角形和长方形子类。每个子类中都有`area`和`perimeter`方法,用于计算对应形状的面积和周长。我们可以通过实例化这些类来计算不同形状的面积和周长,例如:
```python
circle = Circle(5)
print("Circle area:", circle.area())
print("Circle perimeter:", circle.perimeter())
triangle = Triangle(3, 4, 5, 4, 3)
print("Triangle area:", triangle.area())
print("Triangle perimeter:", triangle.perimeter())
rectangle = Rectangle(2, 6)
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: 12
Rectangle perimeter: 16
```
阅读全文