设计三个图形类:Point(点)、Circle(圆)、Triangle(三角形);
时间: 2023-06-11 22:09:54 浏览: 96
好的,以下是三个图形类的设计:
1. Point(点)类:
```python
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
```
2. Circle(圆)类:
```python
class Circle:
def __init__(self, center, radius):
self.center = center # center是一个Point对象,表示圆心
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
def circumference(self):
return 2 * 3.14 * self.radius
```
3. Triangle(三角形)类:
```python
class Triangle:
def __init__(self, p1, p2, p3):
self.p1 = p1 # p1, p2, p3都是Point对象,表示三角形的三个顶点
self.p2 = p2
self.p3 = p3
def area(self):
a = ((self.p1.x - self.p2.x) ** 2 + (self.p1.y - self.p2.y) ** 2) ** 0.5
b = ((self.p2.x - self.p3.x) ** 2 + (self.p2.y - self.p3.y) ** 2) ** 0.5
c = ((self.p1.x - self.p3.x) ** 2 + (self.p1.y - self.p3.y) ** 2) ** 0.5
s = (a + b + c) / 2
return (s * (s - a) * (s - b) * (s - c)) ** 0.5
def perimeter(self):
a = ((self.p1.x - self.p2.x) ** 2 + (self.p1.y - self.p2.y) ** 2) ** 0.5
b = ((self.p2.x - self.p3.x) ** 2 + (self.p2.y - self.p3.y) ** 2) ** 0.5
c = ((self.p1.x - self.p3.x) ** 2 + (self.p1.y - self.p3.y) ** 2) ** 0.5
return a + b + c
```
这三个类可以在其他代码中被实例化和使用。例如,我们可以创建一个圆和一个三角形实例,并计算它们的面积和周长:
```python
p1 = Point(0, 0)
p2 = Point(0, 3)
p3 = Point(4, 0)
triangle = Triangle(p1, p2, p3)
print("Triangle area:", triangle.area())
print("Triangle perimeter:", triangle.perimeter())
center = Point(2, 2)
circle = Circle(center, 5)
print("Circle area:", circle.area())
print("Circle circumference:", circle.circumference())
```
阅读全文