定义类Point描述笛卡尔坐标系上的点,并在该类中编写计算两点间距离的方法distance()。编写公有类TestPoint测试Point类的功能,创建若干点,并输出各点之间的距离。
时间: 2023-05-12 12:07:36 浏览: 179
好的,我可以回答这个问题。以下是Point类的定义和distance()方法的实现:
```python
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, other):
return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5
```
接下来是TestPoint类的实现:
```python
class TestPoint:
def __init__(self):
self.points = [Point(0, 0), Point(1, 1), Point(2, 3), Point(-1, 2)]
def test_distance(self):
for i in range(len(self.points)):
for j in range(i + 1, len(self.points)):
print(f"Distance between point {i+1} and point {j+1}: {self.points[i].distance(self.points[j])}")
```
我们可以创建一个TestPoint对象并调用它的test_distance()方法来测试Point类的功能:
```python
test = TestPoint()
test.test_distance()
```
输出结果如下:
```
Distance between point 1 and point 2: 1.4142135623730951
Distance between point 1 and point 3: 3.605551275463989
Distance between point 1 and point 4: 2.23606797749979
Distance between point 2 and point 3: 2.23606797749979
Distance between point 2 and point 4: 2.8284271247461903
Distance between point 3 and point 4: 4.242640687119285
```
以上就是Point类和TestPoint类的实现,它们可以计算笛卡尔坐标系上两点之间的距离,并输出各点之间的距离。
阅读全文