1. 定义一个抽象类,它包含两个抽象方法面积和周长,从Shape 类派生出三角类,用面积方法来计算面积,用周长来计算周长。然后通过函数设定三角形三边长度为4,5,3,求三角形的面积与周长并输出,且输出三角形的三边长。(输出保留小数点后有效二位)
时间: 2024-05-04 12:18:50 浏览: 77
编写一个抽象类Shape
4星 · 用户满意度95%
以下是Python实现该问题的代码:
```python
import math
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Triangle(Shape):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def area(self):
p = self.perimeter() / 2
return math.sqrt(p * (p - self.a) * (p - self.b) * (p - self.c))
def perimeter(self):
return self.a + self.b + self.c
a, b, c = 4, 5, 3
triangle = Triangle(a, b, c)
print("Triangle sides: {:.2f}, {:.2f}, {:.2f}".format(a, b, c))
print("Triangle area: {:.2f}".format(triangle.area()))
print("Triangle perimeter: {:.2f}".format(triangle.perimeter()))
```
输出结果为:
```
Triangle sides: 4.00, 5.00, 3.00
Triangle area: 6.00
Triangle perimeter: 12.00
```
阅读全文