设计三角形类,继承图形抽象类,计算三角形面积和周长
时间: 2024-02-15 22:32:34 浏览: 56
用类的思想求三角形的周长与面积
5星 · 资源好评率100%
```python
from abc import ABC, abstractmethod
import math
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):
s = (self.a + self.b + self.c) / 2
return math.sqrt(s * (s - self.a) * (s - self.b) * (s - self.c))
def perimeter(self):
return self.a + self.b + self.c
```
使用示例:
```python
t = Triangle(3, 4, 5)
print(t.area())
print(t.perimeter())
```
输出:
```
6.0
12
```
阅读全文